Binding a property to an integer
I've been reading a lot tutorials but somehow nothing works they mention about binding a property to a simple integer.
Here's the setup:
I got 开发者_如何学Goa user-control. I want to bind "private int size" to the width of a border within the XAML-file.
Whats the easiest way to do this?
The same way you'd bind anything else:
<Border BorderThickness="{Binding Size}">
private int _Size;
public int Size
{
get { return _Size; }
set
{
_Size = value;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("Size");
}
}
Of course your class must implement INotifyPropertyChanged
as well.
Another way is to declare a new dependency property and apply TemplateBinding
Here is the control template, where I set bind the Size property to the width.
<Style TargetType="{x:Type local:MyUserControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:MyUserControl}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<TextBox Width="{TemplateBinding Size}"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
public class MyUserControl : Control
{
static MyUserControl()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(MyUserControl), new FrameworkPropertyMetadata(typeof(MyUserControl)));
}
public int Size
{
get { return (int)GetValue(SizeProperty); }
set { SetValue(SizeProperty, value); }
}
// Using a DependencyProperty as the backing store for Size. This enables animation, styling, binding, etc...
public static readonly DependencyProperty SizeProperty =
DependencyProperty.Register("Size", typeof(int), typeof(MyUserControl), new UIPropertyMetadata(20));
}
Reference Link
精彩评论