2

我正在使用 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 属性,如果我CountryViewModelCountryViewModel.SelectedCountry.

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

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

4

1 回答 1

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;
于 2012-11-28T03:49:03.847 回答