将属性绑定到整数

3

我已经阅读了很多教程,但不知何故都没有用。它们提到将属性绑定到一个简单的整数。

以下是设置:

我有一个用户控件。 我想将“private int size”绑定到XAML文件中边框的宽度。

最简单的方法是什么?

2个回答

5

与绑定其他任何内容的方法相同:

<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接口。

1
public class MyUserControl : UserControl, INotifyPropertyChanged { - user7116
1
你要继承自UserControl,而不是实现它。INotifyPropertyChanged是一个接口,你可以实现任意多个接口。 - vcsjones
1
类可以实现多个接口,即使从另一个类继承。将其更改为 MyClass : UserControl, INotifyPropertyChanged - ceyko
此外,@Hedge 所提到的是 @ceykooo 的回答所暗示的,即 WPF 不允许绑定到字段,因此您必须创建一个 CLR 属性(如所示)或 WPF 依赖属性。 - user7116
1
@Danko Durbic:实际上它会起作用,因为依赖属性提供了从整数到Thickness的强制转换。 - user7116
显示剩余7条评论

1

另一种方法是声明一个新的依赖属性并应用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));
}

参考 链接


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接