【问题标题】:Binding to the SelectedItem in a ListBox which is in a DataTemplate for a ContentControl绑定到 ContentControl 的 DataTemplate 中的 ListBox 中的 SelectedItem
【发布时间】:2016-04-30 13:13:54
【问题描述】:

使用 MVVM 方法,我有一个包含 ListBox 的 View 和一个 Grid,我想在其中显示有关 ListBox 中 SelectedItem 的信息。我想将 Grid 的 DataContext 设置为 SelectedItem。

但是,ListBox 的隐藏方式如下:绑定到 DataTemplate 的 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>

这是我的列表视图:

<UserControl>
    <ListBox Name="MyListBox" ItemsSource="{Binding ItemList}"/>
</UserControl>

我正在添加我几年前编写的代码,并且已经离开 WPF 有一段时间了,唉,我对我的数据绑定感到生疏了。我一直在尝试将 SelectedItem 属性添加到 MyListView 和/或 MainWindow 的视图模型中。我预计这可能需要 RelativeSource。

【问题讨论】:

    标签: data-binding


    【解决方案1】:

    哇!我忘记为我的属性指定 OnPropertyChanged 调用。

    在 UserControl ListBox 中,我需要这个:

    ItemsSource="{Binding ItemList}" SelectedItem="{Binding MySelectedItem}"
    

    在主窗口视图模型中,我需要这个:

    public MyItemViewModel MySelectedItem
    {
        get { return _mySelectedItem; }
        set
        {
            _mySelectedItem = value;
            OnPropertyChanged("MySelectedItem");
        }
    }
    

    然后,在主窗口中,绑定很简单:

    <Grid DataContext="{Binding MySelectedItem}">
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-23
      • 2010-12-26
      • 2011-01-02
      • 1970-01-01
      相关资源
      最近更新 更多