【问题标题】:WPF User control binding UIElementWPF 用户控件绑定 UIElement
【发布时间】:2017-10-22 14:32:12
【问题描述】:

我已经创建了我想要绑定 UIElement 的用户控件。我的用户控件:

public partial class TextArea : UserControl
{
    public UIElement AncestorContainer
    {
        get => (UIElement)GetValue(AncestorContainerProperty);
        set => SetValue(AncestorContainerProperty, value);
    }

    public TextArea()
    {
        InitializeComponent();
        DataContext = this;
    }

     public static readonly DependencyProperty AncestorContainerProperty =
                DependencyProperty.Register("AncestorContainerProperty", typeof(UIElement), typeof(TextArea), new PropertyMetadata(null));
 }

在 C# 中创建我的 UserControl 时,它工作正常 - 没有这样的例外:

var textArea = new TextArea
{
    AncestorContainer = Root, // Root is name of Grid
    Text = textItem.Text
};

但是,当尝试在 XAML 中使用绑定时,出现异常:

<ItemsControl ItemsSource="{Binding SuggestedTexts}" >
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <components:TextArea
                AncestorContainer="{Binding ElementName=Sidebar}"/> <!-- Side bar is name of Grid above in XAML -->                                           
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

还有例外:

不能在“ParentContainer”类型“TextArea”中设置“Binding”。 “绑定”只能在DependencyProperty的属性中设置 对象依赖对象。

【问题讨论】:

  • 请注意,您应该永远在 UserControl 中设置 DataContext = this,因为它会破坏对继承 DataContext 属性的绑定。
  • 也就是说,您的错误出在依赖属性声明中。应该是DependencyProperty.Register("AncestorContainer", ...)DependencyProperty.Register(nameof(AncestorContainer), ...)

标签: c# wpf xaml


【解决方案1】:

您在声明依赖属性时有一个拼写错误

DependencyProperty.Register("AncestorContainerProperty", ... 

应该替换为

DependencyProperty.Register("AncestorContainer", ...

或更好

DependencyProperty.Register(nameof(AncestorContainer), ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-06
    • 2012-04-15
    • 1970-01-01
    • 2014-01-14
    • 2010-12-09
    • 2015-01-23
    • 2019-03-01
    相关资源
    最近更新 更多