将属性绑定到自定义控件的另一个属性

时间:2016-10-14 17:07:03

标签: c# wpf xaml binding

我正在基于按钮进行自定义控件,我想将按钮的宽度绑定到类的属性。我查看了thisthisthis,但他们要么不是我要找的,要么不能工作。

Generic.xaml

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:CustomControl">

<Style TargetType="{x:Type local:MyCustomControl}" BasedOn = "{StaticResource {x:Type Button}}">
    <Setter Property = "Background" Value = "LightSalmon" />
    <Setter Property = "Foreground" Value = "Blue"/>
    <Setter Property = "Height" Value = "50"/>
    <Setter Property = "Width" Value = "{Binding MyCustomControl.TextBinding}"/>
    <Setter Property = "VerticalAlignment" Value = "Top"/>
    <Setter Property = "Margin" Value="10"/>
</Style>

</ResourceDictionary>

MyCustomControl.cs

namespace CustomControl
{
public class MyCustomControl : Button
{
    double m_textBinding = 50;
    public double TextBinding
    {
        get { return m_textBinding; }
        set { m_textBinding = value; }
    }
    static MyCustomControl()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(MyCustomControl), 
            new FrameworkPropertyMetadata(typeof(MyCustomControl)));
    }
}
}

如果需要,我可以使用&#34; setter&#34;函数,并手动指定"Width = value;",但我更喜欢使用绑定。目前"{Binding MyCustomControl.TextBinding}"尚无效。

1 个答案:

答案 0 :(得分:1)

这应该有效:

<Setter Property="Width"
        Value="{Binding TextBinding, RelativeSource={RelativeSource Self}}"/>