2010-08-29 82 views
4

我有我添加了一个依赖属性的用户控件:问题数据绑定到一个DependencyProperty在用户控件

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手动设置字词属性的正常工作:

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

不过,我想,然后使用该用户控件的项目模板的一部分,一个列表框和使用数据绑定设置的字:

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

其中产量,当我运行了以下错误:“绑定”

A不能对'字“WordControl”类型的属性进行设置。 '绑定'只能在DependencyObject的DependencyProperty上设置。

由于UserControl继承自DependencyObject,我只能假设问题出在DependencyProperty上,但没有任何Google搜索结果找到答案。

任何想法?

回答

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