我正在基于按钮创建自定义控件,并且我想将按钮的宽度绑定到类的属性。我已经看过this,this和this,但是它们不是我想要的,或者不起作用。
泛型
<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}"
功能无法正常工作。
这应该工作:
<Setter Property="Width"
Value="{Binding TextBinding, RelativeSource={RelativeSource Self}}"/>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句