我有一个usercontrol,它公开这样的公共属性:
public Double ButtonImageHeight
{
get { return imgButtonImage.Height; }
set { imgButtonImage.Height = value; }
}
当我使用该控件时,我希望能够通过类似的样式设置该属性:
<Style x:Key="MyButtonStyle" TargetType="my:CustomButtonUserControl" >
<Setter Property="ButtonImageHeight" Value="100" />
</Style>
我做错了什么?
由于
答案 0 :(得分:3)
感谢Matt,我刚刚发现它,但你是绝对正确的...这是我用过的确切代码,以防它可以帮助别人(我发现的所有例子都在WPF上,Silverlight只是略有不同):< / p>
public static readonly DependencyProperty ButtonImageHeightProperty = DependencyProperty.Register("ButtonImageHeight", typeof(Double), typeof(CustomButtonUserControl),new PropertyMetadata(ButtonImageHeight_PropertyChanged ));
public Double ButtonImageHeight
{
get { return (Double)GetValue(ButtonImageHeightProperty); }
set { SetValue(ButtonImageHeightProperty, value); }
}
private static void ButtonImageHeight_PropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)
{
((CustomButtonUserControl)source).imgButtonImage.Height = (Double)e.NewValue;
}
答案 1 :(得分:1)
该属性需要是依赖属性才能支持样式。
答案 2 :(得分:0)
通过为imgButtonImage传递一个Style,你可以使它更加通用和漂亮,这样你就可以设置多个属性。因此,在您的用户控件中添加依赖项属性,但将其设置为样式:
public static readonly DependencyProperty UseStyleProperty =
DependencyProperty.Register("UseStyle", typeof(Style), typeof(CustomButtonUserControl), new PropertyMetadata(UseStyle_PropertyChanged));
public Style UseStyle
{
get { return (Style)GetValue(UseStyleProperty); }
set { SetValue(UseStyleProperty, value); }
}
private static void UseStyle_PropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)
{
((CustomButtonUserControl)source).imgButtonImage.Style = (Style)e.NewValue;
}
注意我在PropertyChanged函数中如何将控件的样式设置为新样式。
然后当我托管UserControl时,我可以通过样式:
<Style x:Name="MyFancyStyle" TargetType="Button" >
<Setter Property="FontSize" Value="24" />
</Style>
<controls:MyUserControl UseStyle="{StaticResource MyFancyStyle}" />
也适用于VS设计模式! (这是一个奇迹)