我是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 回答
DataGridComboBoxColumn
会给你带来很多问题 . 试试这个:您还应在
Person
类中包含SelectedAddress
属性,以存储ComboBox
中选择的Address
.绑定到
ItemsSource
范围内的属性(在本例中是绑定到DataGrid
的属性)不需要RelativeSource
绑定,这就是您收到错误的原因 . 如果您将DataGrid.ItemsSource
设置为例如PeopleList
并且您想将(在DataGrid
内)ComboBox.ItemsSource
绑定到ViewModel
中的属性但不在PeopleList
内的属性,则需要RelativeSource
.绑定到
ComboBox
的另一件事是,如果将ItemsSource
绑定到strings
以外的对象集合,则必须将DisplayMemberPath
设置为对象中的属性,以使控件显示正确的 Headers . 因此,例如,如果您绑定对象Car
并且它具有名为Name
的string
类型属性,则应将DisplayMemberPath
设置为Name
以使控件显示列表Car.Names
(选择一个仍将导致选择整个对象,而不仅仅是Name
property ) .