Bind ItemsSource and SelectedValue of ComboBox to differentDataContext in WPF?

D

deerchao

Hi there, I have classes like below code:

----------------------------------------
public class Company
{
public Guid CityId {get;set;}
public string Name {get;set;}
}

public class City
{
public Guid Id {get;set;}
public string Name {get;set;}
}

public class Country
{
public Guid Id {get;set;}
public string Name {get;set;}
public IEnumerable<City> Cities {get;set;}
}
----------------------------------------

And I want the user to select a city from a combobox for a city which
is of course in a country:

----------------------------------------
<UserControl>
<TextBox Text="{Binding Name}" />
<StackPanel Name="pnlArea">
<ComboBox DisplayMemberName="Name" ItemsSource="{Bingding}"
IsSynchronizedWithCurrentItem="True" />
<ComboBox DisplayMemberName="Name" ItemsSource="{Binding Cities}"
IsSynchronizedWithCurrentItem="True" SelectedValuePath="Id"
SelectedIndex="{Binding CityId}" />
</StackPanel>
----------------------------------------
DataContext = new Company(...);
pnlArea.DataContext = new List<Country>(...);
----------------------------------------

However this won't work, because CityId is not in the datacontext of
the city combobox (inherited from stack panel). And in order to be
connected with the country combobox, I can't change its DataContext to
the Compnay object.

How can I bind ItemsSource and SelectedValue of the city ComboBox to
both the country list and a company object?
Thanks!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top