问题数据绑定到UserControl上的DependencyProperty

时间:2010-08-29 10:56:04

标签: 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); }
    }

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

<WordGame:WordControl Word="Test"></WordGame:WordControl>

但是,我想将此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>

运行时出现以下错误:

  

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

由于UserControl继承自DependencyObject,我只能假设问题出在DependencyProperty上,但没有数量的Google搜索已找到答案。

有什么想法吗?

1 个答案:

答案 0 :(得分:12)

您的注册错误。这样:

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));