我有两个组合框,分别代表客户代码和客户名称。两者都绑定到相同的对象集合和相同的SelectedItem
。选择客户代码后,我想更新客户名称,反之亦然。
我正在将C#与MVVM模式一起使用。我已经尝试了SelectedItem
和SelectedValue
与selectedvaluepath的所有组合,但似乎无济于事。
这是我的两个组合框:
<ComboBox Name="CmbStockUnitCustomerCode" ItemsSource="{Binding CustomerCodeDtos}"
DisplayMemberPath="Code" SelectedItem="{Binding SelectedCustomer, Mode=TwoWay}"
IsSynchronizedWithCurrentItem="True"></ComboBox>
<ComboBox Name="CmbStockUnitCustomerName" ItemsSource="{Binding CustomerCodeDtos}"
DisplayMemberPath="Name" SelectedItem="{Binding SelectedCustomer, Mode=TwoWay}"
IsSynchronizedWithCurrentItem="True"></ComboBox>
这些是绑定的对象:
public CustomerDto SelectedCustomer
{
get => _selectedcustomer;
set
{
_selectedcustomer = value;
RaisePropertyChanged("SelectedCustomer");
}
}
public class CustomerDto
{
public short Code { get; set; }
public string Name { get; set; }
public CustomerDto(short code, string name)
{
this.Code = code;
this.Name = name;
}
}
public ObservableCollection<CustomerDto> CustomerCodeDtos
{
get => _databaseService.GetAllCustomers();
}
当我更新一个组合框时,我希望另一个组合框更新为对象CustomerDto中的相应值,但是什么也没发生。
答案 0 :(得分:0)
每次引用集合时都在重新创建它,因此SelectedItem引用了另一个对象。实际上,您的两个组合框使用不同的集合作为ItemsSources。将代码更改为
public ObservableCollection<CustomerDto> CustomerCodeDtos
{
get
{
if(_customerCodes==null)
{
_customerCodes = _databaseService.GetAllCustomers();
}
return _customerCodes;
}
}