同步绑定到同一集合和同一选定项目的两个组合框

问题描述 投票:0回答:1

我有两个组合框来表示客户代码和客户名称。两者都绑定到相同的对象集合和相同的SelectedItem。我想在选择客户代码时更新客户名称,反之亦然。

我正在使用带有MVVM模式的C#。我已经尝试了SelectedItemSelectedValue与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中的相应值,但没有任何反应。

c# mvvm combobox selecteditem selectedvalue
1个回答
0
投票

每次引用时都会重新创建集合,因此SelectedItem引用了不同的对象。实际上,您的两个组合框使用不同的集合作为ItemsSources。将代码更改为

public ObservableCollection<CustomerDto> CustomerCodeDtos
{
    get 
    { 
       if(_customerCodes==null)
       {
          _customerCodes = _databaseService.GetAllCustomers();
       }
       return _customerCodes;
    }
}  
© www.soinside.com 2019 - 2024. All rights reserved.