开发者

Problems Data Binding to a DependencyProperty on a UserControl

I have a UserControl that I've added a Dependency Property to:

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

Which works fine when I set the W开发者_StackOverfloword property manually in XAML:

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

However, I want to then use this UserControl as part of the Item Template for a ListBox and use Data Binding to set the word:

    <ListBox Name="WordList" IsEnabled="False" IsHitTestVisible="False">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <WordGame:WordControl Word="{Binding}"></WordGame:WordControl>
                </Grid>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

Which yields the following error when I run it:

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

Since a UserControl inherits from DependencyObject, I can only assume that the problem is with the DependencyProperty, but no amount of Googling has found an answer.

Any ideas?


Your registration is wrong. This:

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

should be:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜