3
我一直在阅读很多教程,但不知何故,他们提到有关将属性绑定到简单整数的问题。将属性绑定到一个整数
下面是设置:
我得到了一个用户控制。 我想将“私人int大小”绑定到XAML文件中边框的宽度。
最简单的方法是什么?
我一直在阅读很多教程,但不知何故,他们提到有关将属性绑定到简单整数的问题。将属性绑定到一个整数
下面是设置:
我得到了一个用户控制。 我想将“私人int大小”绑定到XAML文件中边框的宽度。
最简单的方法是什么?
你绑定什么都用同样的方法:
<Border BorderThickness="{Binding Size}">
private int _Size;
public int Size
{
get { return _Size; }
set
{
_Size = value;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("Size");
}
}
当然你的类必须实现INotifyPropertyChanged
为好。
另一种方式是声明一个新依赖属性和应用TemplateBinding
这里是控制模板,在这里我设置绑定Size属性的宽度。
<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));
}
参考Link
好,我这样做,但它仍然抱怨说,它无法找到的PropertyChanged – Hedge 2011-03-30 15:00:51
'公共类的MyUserControl:用户控件,INotifyPropertyChanged的{' – user7116 2011-03-30 15:05:09
您从用户控件继承,没有实现。 INotifyPropertyChanged是一个接口,您可以根据需要实现多个接口。 – vcsjones 2011-03-30 15:05:27