【发布时间】:2016-10-14 17:07:02
【问题描述】:
我正在制作基于按钮的自定义控件,并且我想将按钮的宽度绑定到类的属性。我查看了this、this 和this,但它们要么不是我想要的,要么不起作用。
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)));
}
}
}
如果需要,我可以只使用“setter”函数,并手动指定"Width = value;",但我更喜欢使用绑定。目前"{Binding MyCustomControl.TextBinding}" 不起作用。
【问题讨论】:
-
TextBinding似乎是一个定义控件宽度的属性的奇怪名称。 -
是的,后来我意识到它是一个双精度,而不是字符串,我只是保留了这个名字,因为我很懒,这只是一个测试。