首页 文章

如何将DataGridComboBoxColumn的datacontext更改为特定的类?

提问于
浏览
2

我是WPF的新手,我对这种情况感到困惑:

class Person{
    string Name;
    List<Address> ListAddresses;
 }

我有一个DataSrid,ItemsSource为 ObservableCollection<Person> . 此集合位于 MainViewModel 类中 .

我想用地址创建一个 DataGridComboBoxColumn .

<DataGrid ItemsSource="{Binding Persons, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">
   <DataGrid.Columns>   
      <DataGridComboBoxColumn ItemsSource="{Binding Path=ListAddresses, RelativeSource={RelativeSource Mode=FindAncestor,
         AncestorType={x:Type local:Person}}}">
      </DataGridComboBoxColumn>      
   </DataGrid.Columns>
</DataGrid>

我收到以下错误:

System.Windows.Data错误:4:无法找到绑定源,引用'RelativeSource FindAncestor,AncestorType ='PersonApp.UL.ViewModels.Person',AncestorLevel ='1'' . BindingExpression:路径= ListAddresses;的DataItem = NULL; target元素是'DataGridComboBoxColumn'(HashCode = 11440639); target属性是'ItemsSource'(输入'IEnumerable')

1 回答

  • 0

    DataGridComboBoxColumn 会给你带来很多问题 . 试试这个:

    <DataGridTemplateColumn Header="Something"
                                SortMemberPath="[SelectedAddress].[property from Address class]">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <ComboBox ItemsSource="{Binding ListAddresses}"
                              SelectedItem="{Binding SelectedAddress, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                              SelectedValuePath="[SelectedAddress].[property from Address class]"
                              DisplayMemberPath="[property from Address class (like Name)]" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    

    您还应在 Person 类中包含 SelectedAddress 属性,以存储 ComboBox 中选择的 Address .

    绑定到 ItemsSource 范围内的属性(在本例中是绑定到 DataGrid 的属性)不需要 RelativeSource 绑定,这就是您收到错误的原因 . 如果您将 DataGrid.ItemsSource 设置为例如 PeopleList 并且您想将(在 DataGrid 内) ComboBox.ItemsSource 绑定到 ViewModel 中的属性但不在 PeopleList 内的属性,则需要 RelativeSource .

    绑定到 ComboBox 的另一件事是,如果将 ItemsSource 绑定到 strings 以外的对象集合,则必须将 DisplayMemberPath 设置为对象中的属性,以使控件显示正确的 Headers . 因此,例如,如果您绑定对象 Car 并且它具有名为 Namestring 类型属性,则应将 DisplayMemberPath 设置为 Name 以使控件显示列表 Car.Names (选择一个仍将导致选择整个对象,而不仅仅是 Name property ) .

相关问题