我有一个用户控件,它具有 Integer 类型的属性,我试图在 XAML 模板中将其设置为绑定(bind)源中的属性的属性。 如果我使用硬编码整数设置属性,即
<MyControl MyIntegerProperty="3" />
这很好用,但如果我尝试
<MyControl MyIntegerProperty="{Binding MyDataContextIntegerProperty}" />
失败了。
我知道 MyDataContext 上的整数属性返回一个有效的整数,并且我知道这种格式有效,正如模板中的正上方,我有一行
<TextBlock Text="{Binding MyDataContextStringProperty}" />
它可以正常工作。
是否需要在我的用户控件整数属性上设置任何标志才能使其正常工作?或者我做错了什么?
谢谢
最佳答案
MyIntegerProperty
需要是 Dependency Property可绑定(bind)...
这是一个例子:
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}" />
关于c# - 在 XAML 中为用户控件设置属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2817228/