首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >WPF用户控件绑定UIElement

WPF用户控件绑定UIElement
EN

Stack Overflow用户
提问于 2017-10-22 14:32:12
回答 1查看 1.5K关注 0票数 0

我已经创建了我的用户控件,我希望能够绑定一个UIElement。我的用户控件:

代码语言:javascript
复制
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#中创建我的C#时,它运行得很好--没有这样的例外:

代码语言:javascript
复制
var textArea = new TextArea
{
    AncestorContainer = Root, // Root is name of Grid
    Text = textItem.Text
};

然而,当试图在XAML中使用绑定时,我得到了一个异常:

代码语言:javascript
复制
<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”中设置“绑定”。“绑定”只能在DependencyProperty对象DependencyObject的属性中设置。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-10-22 17:22:33

在编写时,有一个错误声明依赖项属性。

代码语言:javascript
复制
DependencyProperty.Register("AncestorContainerProperty", ... 

它应该被

代码语言:javascript
复制
DependencyProperty.Register("AncestorContainer", ...

或者更好

代码语言:javascript
复制
DependencyProperty.Register(nameof(AncestorContainer), ...
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46875262

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档