【问题标题】:Why can't WPF bind to UserControl properties?为什么 WPF 不能绑定到 UserControl 属性?
【发布时间】:2009-07-15 08:49:01
【问题描述】:
public class Meh : DependencyObject
{
    public static readonly DependencyProperty MyPropertyProperty =
        DependencyProperty.Register("MyProperty", typeof(string), typeof(Meh));

    public string MyProperty
    {
        get { return (string)GetValue(MyPropertyProperty); }
        set { SetValue(MyPropertyProperty, value); }
    }
}

现在我使用以下代码将其数据绑定到选项卡控件

public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();
        var data = new List<Meh>();
        data.Add(new Meh { MyProperty = "One" });
        data.Add(new Meh { MyProperty = "Two" });
        TabControlViews.ItemsSource = data;
    }
}

选项卡控件的 XAML 如下所示

<TabControl Name="TabControlViews">
    <TabControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding MyProperty}"/>
        </DataTemplate>
    </TabControl.ItemTemplate>
</TabControl>

这工作正常,选项卡“一”、“二”出现在选项卡控件上。但是,如果我将 Meh 的基本类型从 DependencyObject 更改为 UserControl,则选项卡为空白。这是为什么呢?

【问题讨论】:

    标签: wpf data-binding


    【解决方案1】:

    编辑

    我检查了您的代码,似乎在运行时,TabItem 的 ContentPresenter 不会立即从 TabControl 继承 DataContext,因为要显示的项目是 Visual 类型或派生自它。

    这闻起来像一些 TabControl 有趣的行为,因为用 ListBox 替换 TabControl 可以正常工作。 至于问题的具体原因,我不清楚。

    【讨论】:

      【解决方案2】:

      我也遇到了这个问题,我刚刚发现了这个:

      Binding for TabItem's content controls

      看起来你可以创建一个 ItemContainerStyle,而不是使用 ItemTemplate 和 ContentTemplate 属性。我不知道它为什么有效,但它对我有效。

      显然,这对彼得来说有点晚了,但也许它会帮助下一个人遇到这个问题。

      【讨论】:

        【解决方案3】:

        问题在于 ItemsControls 的工作方式。对于 ListBox,它的项目用 ListBoxItem“包装”(假设项目不是 ListBoxItem)。因此,如果您将 UserControl 作为项目添加到 ListBox,它最终会出现在 ListBoxItem.Content 属性中并呈现。

        使用 TabControl,它的项目用 TabItem 包装。与 ListBoxItem 不同,TabItem 派生自 HeaderedContentControl。同样,如果您将 UserControl 作为项目添加到 TabControl,它最终会出现在 TabItem.Content 属性中并呈现。

        现在,如果要添加的项目不是视觉对象(例如 DependencyObject),那么该项目也将分配给 TabItem.Header 属性。因此,在您的情况下,通过将基类从 DependencyObject 切换到 UserControl,您可以切换此行为。

        视觉对象未同时设置为 TabItem.Content 和 TabItem.Header 的原因是因为它可能最终出现在两个位置的视觉对象树中,这很糟糕。

        编辑:

        此外,ItemTemplate 被传递给 TabItem.HeaderTemplate,而不是 TabItem.ContentTemplate(ListBoxItem 就是这种情况)。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-05-23
          • 2014-08-31
          • 2015-04-18
          • 2011-06-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多