首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >样式中的用户控件属性

样式中的用户控件属性
EN

Stack Overflow用户
提问于 2010-12-06 22:11:06
回答 3查看 88关注 0票数 1

我有一个公开公共属性的用户控件,如下所示:

代码语言:javascript
运行
复制
public Double ButtonImageHeight
{
   get { return imgButtonImage.Height; }
   set { imgButtonImage.Height = value; }
}

当我使用该控件时,我希望能够通过这样的样式来设置该属性:

代码语言:javascript
运行
复制
<Style x:Key="MyButtonStyle" TargetType="my:CustomButtonUserControl" >
   <Setter Property="ButtonImageHeight" Value="100" />
</Style>

我做错了什么?

谢谢

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2010-12-06 23:04:11

该属性必须是依赖属性才能支持样式。

票数 1
EN

Stack Overflow用户

发布于 2010-12-06 23:27:23

谢谢你,马特,我自己找到的,不过你说得太对了……下面是我使用的代码,以防它可以帮助其他人(我找到的所有示例都是在WPF上,silverlight只是略有不同):

代码语言:javascript
运行
复制
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;
}
票数 3
EN

Stack Overflow用户

发布于 2013-11-06 07:38:32

您可以通过传递imgButtonImage的样式来使其更加通用和美观,这样您就可以设置多个属性。因此,在您的用户控件中添加依赖属性,但将其设置为样式:

代码语言:javascript
运行
复制
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时,我可以传递样式:

代码语言:javascript
运行
复制
<Style x:Name="MyFancyStyle" TargetType="Button" >
    <Setter Property="FontSize" Value="24" />
</Style>

<controls:MyUserControl UseStyle="{StaticResource MyFancyStyle}"  />

在VS设计模式下也能工作!(这是一个奇迹)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4367223

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档