我查看了您的代码,进行了如下所示的修改,并且成功了。我将右侧视图更改为只有一个文本块以简化它。
MainWindow.xaml.cs(为两个要绑定的视图创建一个视图模型)
public partial class MainWindow
{
public MainWindow()
{
InitializeComponent();
}
public static ProtoViewModel MainViewModel = new ProtoViewModel(Repository.GetContinents());
}
LeftSideView.xaml.cs(将此视图的数据上下文设置为视图模型,并在更改时更新视图模型的选定城市)
public partial class LeftSideView
{
public LeftSideView()
{
InitializeComponent();
this.DataContext = MainWindow.MainViewModel;
}
/// <summary>
/// Update the selected city of the view model
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnTreeSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
(this.DataContext as ProtoViewModel).SelectedCity = e.NewValue as CityViewModel;
}
}
RightSideView.xaml.cs(设置右侧视图使用相同的视图模型)
public partial class RightSideView
{
public RightSideView()
{
InitializeComponent();
this.DataContext = MainWindow.MainViewModel;
}
}
在 RightSideView.xaml 中,我只是放置了如下所示的文本框:
<TextBlock Text="{Binding SelectedCity.Details.City.Name}"/>
When a city on the left view is selected, it will changed the selected city on the view model, therefore, it will updated the selected city name on the right view.
ProtoViewModel 类如下所示:
public class ProtoViewModel : Core.ViewModelBase
{
public ProtoViewModel(IEnumerable<ContinentInfo> continents)
{
Continents =
new ReadOnlyCollection<ContinentViewModel>(
(from continent in continents
select new ContinentViewModel(continent)).ToList());
}
public ViewModels.CityViewModel SelectedCity
{
get { return selectedCity; }
set
{
if(selectedCity != value)
{
selectedCity = value;
OnPropertyChanged("SelectedCity");
}
}
}
private ViewModels.CityViewModel selectedCity;
public ReadOnlyCollection<ContinentViewModel> Continents
{
get { return continents; }
set
{
if (continents != value)
{
continents = value;
OnPropertyChanged("Continents");
}
}
}
private ReadOnlyCollection<ContinentViewModel> continents;
}
我会与你分享修改后的文件,但我不知道该怎么做:)