【发布时间】:2017-07-14 12:16:39
【问题描述】:
GitHub 链接:https://github.com/babakin34/wpf_test/tree/master/WpfApp1
我有以下课程:
视图模型:
public class PersonVM : BindableBase
{
public int ID { get; set; }
private string _lastName;
public string LastName
{
get { return _lastName; }
set { SetProperty(ref _lastName, value); }
}
}
public class MainVM : BindableBase
{
public ObservableCollection<PersonVM> People { get; set; }
private PersonVM _selectedPerson;
public PersonVM SelectedPerson
{
get { return _selectedPerson; }
set { SetProperty(ref _selectedPerson, value); }
}
public MainVM()
{
People = new ObservableCollection<PersonVM>()
{
new PersonVM()
{
ID = 1,
LastName = "AA"
},
new PersonVM()
{
ID = 2,
LastName = "BB"
},
};
SelectedPerson = People.First();
}
}
查看:
<Grid>
<StackPanel>
<ComboBox ItemsSource="{Binding People}"
SelectedItem="{Binding SelectedPerson}"
DisplayMemberPath="LastName"
Margin="0,5,0,25"/>
<DataGrid ItemsSource="{Binding People}"/>
</StackPanel>
</Grid>
如何实现当用户选择空元素时通知 ComboBox 中的“MainVM.SelectedPerson”,这是由 Datagrid 的默认最后一个条目引起的?
PS:我正在使用 Prism,但问题与 Prism 无关。您可以将 BindableBase 替换为 INotifyPropertyChanged。
【问题讨论】:
-
您也应该将
SelectedItem="{Binding SelectedPerson}"添加到DataGrid -
您可以将 DataGrid 的 CanUserAddRows 属性设置为 false 以摆脱最后一个空行。这不是可以在 ComboBox 中选择的实际 PersonVM,而是用于向 DataGrid 添加新项目的占位符...
-
@mm8:我需要 DataGrid 的最后一行,以便用户可以添加新条目。
-
So what do you expect to show in the ComboBox when this row is selected?
-
@Panagiotis Kanavos:它对 ComboBox 没有影响。