【问题标题】:Synchronizing two comboboxes bound to the same collection and to the same selected item同步绑定到同一个集合和同一个选定项的两个组合框
【发布时间】:2019-08-15 12:41:02
【问题描述】:

我有两个组合框来代表客户代码和客户名称。两者都绑定到同一个对象集合和同一个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 中的相应值,但没有任何反应。

【问题讨论】:

  • 您能否也发布 CustomerCodeDtos 集合属性的代码,以确保完整性。
  • CustomerCodeDtos 是一个简单的 CustomerDto 的 ObservableCollection,我从数据库中获取并填充它。
  • 你的问题。你每次都会得到一个新的收藏。获取一次集合,将其存储在实例变量中并引用它。

标签: c# mvvm combobox selecteditem selectedvalue


【解决方案1】:

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

public ObservableCollection<CustomerDto> CustomerCodeDtos
{
    get 
    { 
       if(_customerCodes==null)
       {
          _customerCodes = _databaseService.GetAllCustomers();
       }
       return _customerCodes;
    }
}  

【讨论】:

  • 工作就像一个魅力!没想到会遇到这样的问题!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-07
  • 2022-01-11
  • 2023-03-30
  • 1970-01-01
  • 2012-10-13
  • 2013-06-15
相关资源
最近更新 更多