开发者

Setting a property in XAML for a User Control

开发者 https://www.devze.com 2022-12-30 12:55 出处:网络
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.

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. If I set the property using a hard coded开发者_高级运维 integer i.e.

<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

 <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? Or am i doing something else wrong?

Thanks


MyIntegerProperty needs to be a Dependency Property to be bindable...

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 MyInteger="{Binding MyDataContextIntegerProperty}" />


You need to define MyIntegerProperty as a Dependency Property. 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); }
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消