Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems Data Binding to a DependencyProperty on a UserControl

Tags:

binding

wpf

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 Word 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?

like image 856
littlecharva Avatar asked Dec 17 '22 22:12

littlecharva


1 Answers

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));
like image 185
Kent Boogaart Avatar answered Jun 02 '23 18:06

Kent Boogaart