gpt4 book ai didi

wpf - 问题数据绑定(bind)到 UserControl 上的 DependencyProperty

转载 作者:行者123 更新时间:2023-12-04 22:25:26 25 4
gpt4 key购买 nike

我有一个用户控件,我已将依赖属性添加到:

public partial class WordControl : UserControl
{

// Using a DependencyProperty as the backing store for WordProperty. This enables animation, styling, binding, etc...
public static readonly DependencyProperty WordProperty =
DependencyProperty.Register("WordProperty", typeof(string), typeof(WordControl), new FrameworkPropertyMetadata("", OnWordChange));

public string Word
{
get { return (string)GetValue(WordProperty); }
set { SetValue(WordProperty, value); }
}

当我在 XAML 中手动设置 Word 属性时,效果很好:
<WordGame:WordControl Word="Test"></WordGame:WordControl>

但是,我想将此 UserControl 用作 ListBox 的项目模板的一部分,并使用数据绑定(bind)来设置单词:
    <ListBox Name="WordList" IsEnabled="False" IsHitTestVisible="False">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<WordGame:WordControl Word="{Binding}"></WordGame:WordControl>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

当我运行它时会产生以下错误:

A 'Binding' cannot be set on the 'Word' property of type 'WordControl'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject.



由于 UserControl 继承自 DependencyObject,我只能假设问题出在 DependencyProperty 上,但没有多少谷歌搜索找到答案。

有任何想法吗?

最佳答案

您的注册错误。这:

public static readonly DependencyProperty WordProperty =
DependencyProperty.Register("WordProperty", typeof(string), typeof(WordControl), new FrameworkPropertyMetadata("", OnWordChange));

应该:
public static readonly DependencyProperty WordProperty =
DependencyProperty.Register("Word", typeof(string), typeof(WordControl), new FrameworkPropertyMetadata("", OnWordChange));

关于wpf - 问题数据绑定(bind)到 UserControl 上的 DependencyProperty,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3594437/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com