【问题标题】:How to bind Selected item of Combobox to two different Property?如何将 Combobox 的选定项绑定到两个不同的属性?
【发布时间】:2012-11-11 15:50:53
【问题描述】:

我正在使用 MVVM 模式开发项目。在项目中我有两个视图模型

  1. CountryViewModel 和 2. EmpViewModel

在 countryviewmodel 中,我存储了有关国家、州、城市等的信息。

在 EmpViewModel 中,我有一个控件,该控件具有显示国家名称的组合框,并且所选值设置为 CountryViewModel 中的国家 ID。

代码如下:

<ComboBox Grid.Row="0" Grid.Column="1" Margin="3"
             ItemsSource="{Binding CountryViewModel.Countries}" SelectedValue="{Binding Title}"
             SelectedItem="{Binding CountryViewModel.SelectedCountry,Mode=TwoWay}"                               
             SelectedValuePath="Country_Id" DisplayMemberPath="Title">
    </ComboBox>

这工作正常。

我在 EmpViewModel 中有本地属性国家/地区 ID,并希望将其绑定到 Combobox 的 SelectedValue 属性,如果我从 CountryViewModel.SelectedCountry 中删除 CountryViewModel,我可以获得该属性。

但问题是我有另一个依赖于国家组合框的状态组合框。 编辑:即在 Country ViewModel 中,当 SelectedCountry 更改时,我调用了 GetAllState() 方法。

那么我可以将 Combobox 的 SelectedValue 属性绑定到 CountryViewModel 中的 CountryViewModel.SelectedCountry 和 EmpViewModel 中的 Country_Id 吗?

【问题讨论】:

    标签: mvvm binding combobox silverlight-5.0


    【解决方案1】:

    我找到了解决方法

    我在接口中写了以下方法:

     public interface IViewModel
    {
        T GetValue<T>(string propertyName);
    }
    

    在国家视图模型中,我将此方法实现为:

     public override T GetValue<T>(string propertyName)
        {
            T result = default(T);
            result = (T)Convert.ChangeType(this.SelectedCountry, typeof(T), null); }
    

    在 Emp View Model 中,我添加了以下行:

    newEmp.Country_Id = this.CountryViewModel.GetValue<Country>("SelectedCountry").Country_Id;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-28
      • 1970-01-01
      • 1970-01-01
      • 2011-03-06
      • 2011-04-17
      • 2014-12-08
      • 2011-05-02
      • 2019-04-30
      相关资源
      最近更新 更多