[英]Setting a property in XAML for a User Control
I have a user control that has a property of type Integer, that i am trying to set in the XAML Template to be that of a property within the bindingsource.我有一个用户控件,它具有 Integer 类型的属性,我试图在 XAML 模板中将其设置为绑定源中的属性。 If I set the property using a hard coded integer ie如果我使用硬编码 integer ie 设置属性
<MyControl MyIntegerProperty="3" />
This works fine, but if i try这工作正常,但如果我尝试
<MyControl MyIntegerProperty="{Binding MyDataContextIntegerProperty}" />
it fails.它失败。
I know that the integer property on MyDataContext is returning a valid integer, and i know that this format works, as directly above this in the template, i have the line我知道 MyDataContext 上的 integer 属性返回一个有效的 integer,而且我知道这种格式有效,正如模板中的正上方,我有一行
<TextBlock Text="{Binding MyDataContextStringProperty}" />
which works correctly.哪个工作正常。
Is there any flag that i need to set on my User Controls Integer property to allow this to work?是否需要在我的用户控件 Integer 属性上设置任何标志才能使其正常工作? Or am i doing something else wrong?还是我做错了什么?
Thanks谢谢
MyIntegerProperty
needs to be a Dependency Property to be bindable... MyIntegerProperty
需要成为可绑定的依赖属性...
Here is an example:这是一个例子:
public static readonly DependencyProperty MyIntegerProperty =
DependencyProperty.Register("MyInteger", typeof(Integer), typeof(MyControl));
public int MyInteger
{
get { return (int)GetValue(MyIntegerProperty); }
set { SetValue(MyIntegerProperty, value); }
}
The XAML definition of MyControl would then become: MyControl 的 XAML 定义将变为:
<MyControl MyInteger="{Binding MyDataContextIntegerProperty}" />
You need to define MyIntegerProperty
as a Dependency Property.您需要将MyIntegerProperty
定义为依赖属性。 You could define it like this:你可以这样定义它:
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); }
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.