使用MVVM方法,我有一个View,它包含一个ListBox,还有一个Grid,我想在其中显示ListBox中SelectedItem的信息。我想将Grid的DataContext设置为SelectedItem。
但是,ListBox隐藏如下:ContentControl绑定到DataTemplate,它是包含ListBox的UserControl视图。
以下是我不确定如何绑定的MainWindow Grid:
<Grid DataContext="{Binding ElementName=MyList, ????}">
以下是同一视图中的ContentControl:
<ContentControl x:Name="MyList"
Content="{Binding}"
ContentTemplate="{StaticResource MyListTemplate}"/>
以下是同一视图中的数据模板:
<Window.Resources>
<DataTemplate x:Key="MyListTemplate">
<v:MyListView/>
</DataTemplate>
</Window.Resources>
这是MyListView:
<UserControl>
<ListBox Name="MyListBox" ItemsSource="{Binding ItemList}"/>
</UserControl>
我正在添加几年前写的代码,并且已经离开WPF一段时间了,所以,我的数据绑定生锈了。我一直在尝试将SelectedItem属性添加到MyListView和/或MainWindow的视图模型中。我希望这可能需要RelativeSource。
答案 0 :(得分:0)
卫生署!我忘了为我的财产指定OnPropertyChanged调用。
在UserControl ListBox中,我需要这个:
ItemsSource="{Binding ItemList}" SelectedItem="{Binding MySelectedItem}"
在主窗口视图模型中,我需要这个:
public MyItemViewModel MySelectedItem
{
get { return _mySelectedItem; }
set
{
_mySelectedItem = value;
OnPropertyChanged("MySelectedItem");
}
}
然后,在主窗口中,绑定就是:
<Grid DataContext="{Binding MySelectedItem}">