0

我有一个 ObservableCollection,它从从 Postgres 数据库填充的 DataTable 中获取数据。我需要将此 ObservableCollection 绑定到 DataGrid 中的 ComboBoxColumn。我已经看到了很多关于如何做到这一点的例子,但我经常错过一些东西。

编辑:这是新的更新代码,除了 INotifyPropertyChanged 我只设置为“名称”(还)

namespace Country_namespace

{

public class CountryList : ObservableCollection<CountryName>
{
    public CountryList():base()
    {

      // Make the DataTables and fill them           



    foreach(DataRow row in country.Rows)
    {
       Add(new CountryName((string)row.ItemArray[1], (int)row.ItemArray[0]));
   }           
    }
}

public class CountryName: INotifyPropertyChanged
{
    private string name;
    private int id_country;
    public event PropertyChangedEventHandler PropertyChanged;

    public CountryName(string country_name, int id)
    {
        this.name = country_name;
        this.id_country = id;
    }

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

    public int idcountry
    {
        get { return id_country; }
        set { id_country = value; }
    }
    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }
}

}

XAML:

xmlns:c="clr-namespace:Country_namespace"

<Windows.Resources>
<c:CountryList x:Key="CountryListData"/>
</Windows.Resources>

数据网格列:

<dg:DataGridTemplateColumn Header="country">
                                <dg:DataGridTemplateColumn.CellTemplate>
                                    <DataTemplate>
                                        <ComboBox ItemsSource="{Binding Source={StaticResource CountryListData}}"  DisplayMemberPath="Name"></ComboBox>

                                    </DataTemplate>
                                </dg:DataGridTemplateColumn.CellTemplate>
                            </dg:DataGridTemplateColumn>
4

1 回答 1

0

首先。您可以绑定到公共属性。

country_ 似乎没有公共财产。

第二,如果绑定不起作用,您总是必须先检查数据上下文,然后再检查绑定路径。你可以使用Snoop执行此操作

编辑:

你没有为你的网格发布你的 itemssource。所以这里有一些假设。

<DataGrid ItemsSource="{Binding MySource}">
  ...
    <ComboBox ItemsSource="{Binding MySourcePropertyForCountries}"/>

--> 当您的 MySource 对象项具有公共属性 MySourcePropertyForCountries 时,这将起作用。

但是,如果您想将组合框绑定到 MySource 对象之外的列表。那么你必须使用某种 relativeSourcebinding 或 elementbinding。

<DataGrid x:Name="grd" ItemsSource="{Binding MySource}">
  ...
    <ComboBox ItemsSource="{Binding ElementName=grd, Path=DataContext.MyCountries}"/>

--> 当数据网格的数据上下文具有属性 MyCountries 时,这将起作用

于 2013-05-27T07:11:02.397 回答