DoctorAV
DoctorAV

Reputation: 1189

How to bind Selected item of Combobox to two different Property?

I am developing project using MVVM pattern.In the project I have two viewmodel namely

  1. CountryViewModel and 2. EmpViewModel

In countryviewmodel I have stored information about country,state,city etc.

In EmpViewModel I have a control which have combo box which displays country name and selected value is set to country id which are in CountryViewModel.

Here is code:

<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>

This is working fine.

I have local property country id in EmpViewModel and want to bind it to SelectedValue property of Combobox which I can get if I remove CountryViewModel from CountryViewModel.SelectedCountry.

But problem is I have another combobox for state which is dependent on Country combo box. Edit: i.e in Country ViewModel I have called method GetAllState() when SelectedCountry changes.

So can I bind SelectedValue property of Combobox to both CountryViewModel.SelectedCountry from CountryViewModel and Country_Id from EmpViewModel?

Upvotes: 2

Views: 550

Answers (1)

DoctorAV
DoctorAV

Reputation: 1189

I found a workaround

I have write following method in an interface:

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

In country view model I implement this method as:

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

And in Emp View Model I added following line:

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

Upvotes: 1

Related Questions