我有一个公开公共属性的用户控件,如下所示:
public Double ButtonImageHeight
{
get { return imgButtonImage.Height; }
set { imgButtonImage.Height = value; }
}当我使用该控件时,我希望能够通过这样的样式来设置该属性:
<Style x:Key="MyButtonStyle" TargetType="my:CustomButtonUserControl" >
<Setter Property="ButtonImageHeight" Value="100" />
</Style>我做错了什么?
谢谢
发布于 2010-12-06 23:04:11
该属性必须是依赖属性才能支持样式。
发布于 2010-12-06 23:27:23
谢谢你,马特,我自己找到的,不过你说得太对了……下面是我使用的代码,以防它可以帮助其他人(我找到的所有示例都是在WPF上,silverlight只是略有不同):
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;
}发布于 2013-11-06 07:38:32
您可以通过传递imgButtonImage的样式来使其更加通用和美观,这样您就可以设置多个属性。因此,在您的用户控件中添加依赖属性,但将其设置为样式:
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设计模式下也能工作!(这是一个奇迹)
https://stackoverflow.com/questions/4367223
复制相似问题