Silverlight 样式中的用户控件属性
我有一个usercontrol,它公开如下公共属性:Silverlight 样式中的用户控件属性,silverlight,xaml,Silverlight,Xaml,我有一个usercontrol,它公开如下公共属性: public Double ButtonImageHeight { get { return imgButtonImage.Height; } set { imgButtonImage.Height = value; } } 使用该控件时,我希望能够通过以下样式设置该属性: <Style x:Key="MyButtonStyle" TargetType="my:CustomButtonUserControl" >
public Double ButtonImageHeight
{
get { return imgButtonImage.Height; }
set { imgButtonImage.Height = value; }
}
使用该控件时,我希望能够通过以下样式设置该属性:
<Style x:Key="MyButtonStyle" TargetType="my:CustomButtonUserControl" >
<Setter Property="ButtonImageHeight" Value="100" />
</Style>
我做错了什么
谢谢为了支持样式,属性必须是依赖属性。为了支持样式,属性必须是依赖属性。谢谢Matt,我刚找到它,但你绝对正确。。。下面是我使用的代码,以防它可以帮助其他人(我发现的所有示例都是在WPF上,silverlight只是略有不同):
谢谢马特,我自己刚找到的,但你绝对是对的。。。下面是我使用的代码,以防它可以帮助其他人(我发现的所有示例都是在WPF上,silverlight只是略有不同):
通过传递imgButtonImage的样式,您可以使它更通用、更美观,这样您就可以设置多个属性。因此,在用户控件中添加dependency属性,但将其设置为样式:
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设计模式下工作!(这是一个奇迹)通过为imgButtonImage传递一个样式,您可以设置多个属性,从而使它更加通用和美观。因此,在用户控件中添加dependency属性,但将其设置为样式:
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设计模式下工作!(这是一个奇迹)显示xaml,您实际将UserControl放置在另一个中,以及如何将样式分配给它。显示xaml,您实际将UserControl放置在另一个中,以及如何将样式分配给它。