2010-05-12 72 views
2

我有一个具有Integer类型属性的用户控件,我试图在XAML模板中将其设置为bindingsource中属性的属性。 如果我使用硬编码的整数,即在XAML中为用户控件设置属性

<MyControl MyIntegerProperty="3" /> 

这工作得很好,但如果我尝试

<MyControl MyIntegerProperty="{Binding MyDataContextIntegerProperty}" /> 

失败设置属性。

我知道,在MyDataContext整数属性返回一个有效的整数,我知道,这种格式的作品,直接上面这个模板,我也行

<TextBlock Text="{Binding MyDataContextStringProperty}" /> 

其正常工作。

是否有任何标记需要在我的用户控件整数属性上设置以允许此工作?还是我在做别的事情?

感谢

+1

是你的财产DependencyProperty? – Yurec 2010-05-12 08:59:51

+0

嗨@Yurec,不,它不是,我从下面的回应猜测,它需要。干杯 – Ben 2010-05-12 10:17:51

回答

2

MyIntegerProperty需要一个Dependency Property是绑定...

下面是一个例子:

public static readonly DependencyProperty MyIntegerProperty = 
    DependencyProperty.Register("MyInteger", typeof(Integer), typeof(MyControl)); 

public int MyInteger 
{ 
    get { return (int)GetValue(MyIntegerProperty); } 
    set { SetValue(MyIntegerProperty, value); } 
} 

MyControl的XAML定义将随即成为:

<MyControl MyInteger="{Binding MyDataContextIntegerProperty}" /> 
0

您需要将MyIntegerProperty定义为依赖项属性。你可以这样定义:

public class MyControl : UserControl 
{ 
    public static readonly DependencyProperty MyIntegerProperty = 
      DependencyProperty.Register("MyInteger", typeof(Integer),typeof(MyControl), <MetaData>); 

    public int MyInteger 
    { 
     get { return (int)GetValue(MyIntegerProperty); } 
     set { SetValue(MyIntegerProperty, value); } 
    } 
}