【问题标题】:Is it possible to bind a WPF control to multiple data contexts?是否可以将 WPF 控件绑定到多个数据上下文?
【发布时间】:2009-07-29 11:40:00
【问题描述】:

我编写了一个 UserControl,它的 DataContext 包含一个集合和一个 bool 属性。该集合在具有自定义列模板的数据网格中显示(和编辑)。列中控件的DataContext当然是UserControl的DataContext集合中的一项。但是,我需要将列中控件的一个属性绑定到 UserControl 的 DataContext 的 bool 属性而不是集合项。

您对如何解决这个问题有任何想法吗?

最好的问候,奥利弗

【问题讨论】:

    标签: wpf data-binding


    【解决方案1】:

    我直接从另一个帖子的回答中提取了这一点

    Getting at the "parent" of a databound object?

    这是我认为可能与您尝试做的事情有关的帖子中的代码:

    <ListBox Name="list" ItemsSource="{Binding Items}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <TextBlock Text="{Binding}"/>
                    <ComboBox ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}, Path=DataContext.Values}"/>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
    

    在这种情况下,ListBox 的 DataContext 基本上包含一些列表,并且 ItemTemplate 的 DataTemplate 中的一个组合框绑定到 ListBox 的 DataContext 的不同成员,而 ItemsSource 绑定到 DataContext 的 Items 成员。我认为这可能适用于您的 DataGrid 和列模板。

    【讨论】:

      【解决方案2】:

      解决方案 1. 创建一个包含集合和 bool 属性的自定义类,并将 DataContext 设置为该类的实例。

      解决方案 2. 将用户控件的 DataContext 设置为集合,并将 bool 属性添加到您的用户控件。

      XAML:

      <UserControl x:Class="DataContextDemo.UserControl1"
          xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
          xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
          x:Name="self">
          <StackPanel>
              <ListBox ItemsSource="{Binding}" />
              <CheckBox IsChecked="{Binding Path=MyBoolProp, ElementName=self}" />
          </StackPanel>
      </UserControl>
      

      后面的代码:

      using System.Windows;
      using System.Windows.Controls;
      
      namespace DataContextDemo
      {
          public partial class UserControl1 : UserControl
          {
              public UserControl1()
              {
                  InitializeComponent();
              }
      
              public bool MyBoolProp
              {
                  get { return (bool)GetValue(MyBoolPropProperty); }
                  set { SetValue(MyBoolPropProperty, value); }
              }
      
              public static readonly DependencyProperty MyBoolPropProperty =
                  DependencyProperty.Register("MyBoolProp", 
                                              typeof(bool), 
                                              typeof(UserControl1), 
                                              new UIPropertyMetadata(true));
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2010-10-15
        • 1970-01-01
        • 1970-01-01
        • 2012-09-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-15
        • 2011-10-07
        • 2010-10-13
        相关资源
        最近更新 更多