问题数据绑定到UserControl上的DependencyProperty

lit*_*rva 4 wpf binding

我有一个UserControl我已经添加了一个依赖属性:

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); }
    }
Run Code Online (Sandbox Code Playgroud)

当我在XAML中手动设置Word属性时,哪个工作正常:

<WordGame:WordControl Word="Test"></WordGame:WordControl>
Run Code Online (Sandbox Code Playgroud)

但是,我想将此UserControl用作ListBox的Item Template的一部分,并使用Data Binding来设置单词:

    <ListBox Name="WordList" IsEnabled="False" IsHitTestVisible="False">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <WordGame:WordControl Word="{Binding}"></WordGame:WordControl>
                </Grid>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
Run Code Online (Sandbox Code Playgroud)

运行时会出现以下错误:

无法在"WordControl"类型的"Word"属性上设置"绑定".'绑定'只能在DependencyObject的DependencyProperty上设置.

由于UserControl继承自DependencyObject,我只能假设问题在于DependencyProperty,但没有任何数量的Google搜索找到了答案.

有任何想法吗?

Ken*_*art 12

您的注册有误.这个:

public static readonly DependencyProperty WordProperty =
        DependencyProperty.Register("WordProperty", typeof(string), typeof(WordControl), new FrameworkPropertyMetadata("", OnWordChange));
Run Code Online (Sandbox Code Playgroud)

应该:

public static readonly DependencyProperty WordProperty =
        DependencyProperty.Register("Word", typeof(string), typeof(WordControl), new FrameworkPropertyMetadata("", OnWordChange));
Run Code Online (Sandbox Code Playgroud)