Setting a property in XAML for a custom control
I have a user control that has a property of type Integer, which I am trying to set in a XAML template as a property of a property in the bindings source. If I set the property using a hard coded integer ie
<MyControl MyIntegerProperty="3" />
This works great, but if I try
<MyControl MyIntegerProperty="{Binding MyDataContextIntegerProperty}" />
he does not work.
I know that the integer property in MyDataContext returns a valid integer and I know that this format works like directly above this in the template, I have the line
<TextBlock Text="{Binding MyDataContextStringProperty}" />
which works correctly.
Is there any flag I need to set for the User Controls Integer property for this to work? Or am I doing something else wrong?
thanks
a source to share
MyIntegerProperty must be a Dependency Property for binding ...
Here's 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 XCML definition of MyControl would be as follows:
<MyControl MyInteger="{Binding MyDataContextIntegerProperty}" />
a source to share
You need to define MyIntegerProperty
as a dependency property. You can 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); }
}
}
a source to share