ObservableCollection与INotifyPropertyChanged变为DatagridComboboxColumn绑定 [英] ObservableCollection with INotifyPropertyChanged into DatagridComboboxColumn Binding

查看:151
本文介绍了ObservableCollection与INotifyPropertyChanged变为DatagridComboboxColumn绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的小项目看起来现在完全不同了。现在我有ObservableCollection PackagesList 与我要绑定整个DataGrid(通过绑定路径)和ObservableCollection DestinationItememsSource 其中的数据我存储DataGridComboboxColumn(作为ItemsSourceBinding)的情况。 DatagridComboboxColumn中的SelectedItem属性是 PackageInfo 中的一个值(它是 DestinationNames 案例中的一个)。绑定在DatagridTextBoxColumns是确定。



XAML:

 <窗口x:Class =test01.MainWindow
xmlns =http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x =http://schemas.microsoft .com / winfx / 2006 / xaml
Title =MainWindowHeight =300Width =400Loaded =Window_Loaded>
< Grid>
< Border x:Name =mainBorderMargin =20>
< DataGrid x:Name =mainDataGridx:Uid =mainDataGridAutoGenerateColumns =False
AlternationCount =2SelectionMode =SingleHorizo​​ntalAlignment =Stretch>
< DataGrid.Columns>
< DataGridTextColumn Binding ={Binding Path = id}
标题=ID宽度=自动IsReadOnly =True/>
< DataGridTextColumn Binding ={Binding Path = name}
Header =NameWidth =AutoIsReadOnly =True/>
< DataGridTextColumn Binding ={Binding Path = quantity}
标题=数量宽度=自动IsReadOnly =True/>
< DataGridTextColumn Binding ={Binding Path = price}
Header =PriceWidth =AutoIsReadOnly =True/>
< DataGridComboBoxColumn ItemsSource ={Binding DestinationItemsSource}
SelectedItemBinding ={Binding Path = destination,UpdateSourceTrigger = PropertyChanged}
Header =DestinationWidth =Auto/>
< /DataGrid.Columns>
< / DataGrid>
< / Border>
< / Grid>
< / Window>

C#:

 code> public class PackageInfo 
{
public int id {get;组; }
public string name {get;组; }
public int quantity {get;组; }
public double price {get;组; }
public string destination {get;组;
}

public class DestinationNames:INotifyPropertyChanged
{
public string name {get;组; }

public event PropertyChangedEventHandler PropertyChanged;

public DestinationNames(string value)
{
this.name = value;
}

public string DestinationName
{
get {return name; }
set
{
name = value;
OnPropertyChanged(DestinationName);
}
}

protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if(handler!= null)
{
handler(this,new PropertyChangedEventArgs(name));
}
}
}


public partial class MainWindow:Window
{
public ObservableCollection< DestinationNames> DestinationItememsSource {get;组; }
public ObservableCollection< PackageInfo> PackagesList {get;组; }

public MainWindow()
{
InitializeComponent();
}

public void Window_Loaded(object sender,RoutedEventArgs e)
{
LoadPackages();
}

public void LoadPackages()
{
DestinationItememsSource = new ObservableCollection< DestinationNames>();
DestinationItememsSource.Add(new DestinationNames(London));
DestinationItememsSource.Add(new DestinationNames(Plymouth));
DestinationItememsSource.Add(new DestinationNames(Birmingham));
DestinationItememsSource.Add(new DestinationNames(Cambridge));

PackagesList = new ObservableCollection< PackageInfo>();
PackagesList.Add(new PackageInfo {id = 1,name =Potato,quantity = 3,price = 2.2,destination =London});
PackagesList.Add(new PackageInfo {id = 2,name =Tomato,quantity = 5,price = 3.8,destination =Plymouth});
PackagesList.Add(new PackageInfo {id = 3,name =Carrot,quantity = 1,price = 5.1,destination =London});
PackagesList.Add(new PackageInfo {id = 4,name =Pea,quantity = 6,price = 1.8,destination =Plymouth});
PackagesList.Add(new PackageInfo {id = 5,name =Bean,quantity = 2,price = 1.5,destination =Birmingham});
mainDataGrid.ItemsSource = PackagesList;
}
}

如何正确绑定DatagridComboboxColumn?我应该使用INotifyCollectionChanged吗?如果我想要datagrid中的所有数据将自动与ObservableCollection同步?请帮助一些例子。

解决方案

您对DestinationItememsSource的绑定不起作用,因为它不是 PackageInfo 对象。您也无法通过FindAncestor或ElementName绑定绑定到Windows DataContext,因为DataGrid列不会添加到视觉树中。



我可以想到的一个解决方案是使用 CollectionViewSource

 < Window.Resources> 
< CollectionViewSource Source ={Binding RelativeSource = {RelativeSource Self},Path = DestinationItememsSource}x:Key =destinations>
<! - 这里您还可以添加组和SortDescriptions - >
< / CollectionViewSource>
< /Window.Resources>
< DataGridComboBoxColumn ItemsSource ={Binding Source = {StaticResource ResourceKey = destinations}}... />

我不能测试它atm,因为我还在下载VS 2012。^^



另一个人将简单地将一个目的地列表添加到您的PackageInfo对象(但这会导致很多冗余)。


My little project looks now quite different. Now I have ObservableCollection PackagesList with data which I want to bind with whole DataGrid (via Binding Path) and ObservableCollection DestinationItememsSource where I store cases for DataGridComboboxColumn (as ItemsSourceBinding). SelectedItem property in DatagridComboboxColumn is one value from PackageInfo (and it is one of DestinationNames cases ofc). Binding on DatagridTextBoxColumns is ok.

XAML:

<Window x:Class="test01.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="300" Width="400" Loaded="Window_Loaded">
    <Grid>
        <Border x:Name="mainBorder" Margin="20">
            <DataGrid x:Name="mainDataGrid" x:Uid="mainDataGrid" AutoGenerateColumns="False"
                       AlternationCount="2" SelectionMode="Single" HorizontalAlignment="Stretch">
                <DataGrid.Columns>
                    <DataGridTextColumn Binding="{Binding Path=id}"
                                    Header="ID" Width="Auto" IsReadOnly="True"/>
                    <DataGridTextColumn Binding="{Binding Path=name}"
                                    Header="Name" Width="Auto" IsReadOnly="True"/>
                    <DataGridTextColumn Binding="{Binding Path=quantity}"
                                    Header="Quantity" Width="Auto" IsReadOnly="True"/>
                    <DataGridTextColumn Binding="{Binding Path=price}"
                                    Header="Price" Width="Auto" IsReadOnly="True"/>
                    <DataGridComboBoxColumn ItemsSource="{Binding DestinationItemsSource}" 
                                                    SelectedItemBinding="{Binding Path=destination, UpdateSourceTrigger=PropertyChanged}"
                                                    Header="Destination" Width="Auto"/>
                </DataGrid.Columns>
            </DataGrid>
        </Border>
    </Grid>
</Window>

C#:

public class PackageInfo
    {
        public int id { get; set; }
        public string name { get; set; }
        public int quantity { get; set; }
        public double price { get; set; }
        public string destination { get; set; }
    }

    public class DestinationNames : INotifyPropertyChanged
    {
        public string name { get; set; }

        public event PropertyChangedEventHandler PropertyChanged;

        public DestinationNames(string value)
        {
            this.name = value;
        }

        public string DestinationName
        {
            get { return name; }
            set
            {
                name = value;
                OnPropertyChanged("DestinationName");
            }
        }

        protected void OnPropertyChanged(string name)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(name));
            }
        }
    }


    public partial class MainWindow : Window
    {
        public ObservableCollection<DestinationNames> DestinationItememsSource { get; set; }
        public ObservableCollection<PackageInfo> PackagesList { get; set; }

        public MainWindow()
        {
            InitializeComponent();
        }

        public void Window_Loaded(object sender, RoutedEventArgs e)
        {
            LoadPackages();
        }

        public void LoadPackages()
        {
            DestinationItememsSource = new ObservableCollection<DestinationNames>();
            DestinationItememsSource.Add(new DestinationNames("London"));
            DestinationItememsSource.Add(new DestinationNames("Plymouth"));
            DestinationItememsSource.Add(new DestinationNames("Birmingham"));
            DestinationItememsSource.Add(new DestinationNames("Cambridge"));

            PackagesList = new ObservableCollection<PackageInfo>();
            PackagesList.Add(new PackageInfo { id = 1, name = "Potato", quantity = 3, price = 2.2, destination = "London" });
            PackagesList.Add(new PackageInfo { id = 2, name = "Tomato", quantity = 5, price = 3.8, destination = "Plymouth" });
            PackagesList.Add(new PackageInfo { id = 3, name = "Carrot", quantity = 1, price = 5.1, destination = "London" });
            PackagesList.Add(new PackageInfo { id = 4, name = "Pea", quantity = 6, price = 1.8, destination = "Plymouth" });
            PackagesList.Add(new PackageInfo { id = 5, name = "Bean", quantity = 2, price = 1.5, destination = "Birmingham" });
            mainDataGrid.ItemsSource = PackagesList;
        }
    }

How to bind this DatagridComboboxColumn properly? Should I use INotifyCollectionChanged ?? What if I want to all data in datagrid will be automatically synced with ObservableCollection ?? Please help with some example.

解决方案

Your binding to DestinationItememsSource does not work, because it isnt part of the PackageInfo object. You also cant bind to the Windows DataContext via FindAncestor or ElementName-binding because DataGrid-Columns wont be added to the visual tree.

One solution I can think of is using the CollectionViewSource:

<Window.Resources>
    <CollectionViewSource Source="{Binding RelativeSource={RelativeSource Self}, Path=DestinationItememsSource}" x:Key="destinations">
        <!--here you can also add Group and SortDescriptions-->
    </CollectionViewSource>
</Window.Resources>
<DataGridComboBoxColumn ItemsSource="{Binding Source={StaticResource ResourceKey=destinations}}".../> 

I cant test it atm, because I'm still downloading VS 2012.^^

Anotherone would be to simply add a List of Destinations to your PackageInfo object (but this would cause a lot of redundancies).

这篇关于ObservableCollection与INotifyPropertyChanged变为DatagridComboboxColumn绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆