Wpf设计师无法应用Style

时间:2013-10-14 13:48:31

标签: wpf styles code-behind

在Wpf中,我从Button类继承:

public class MenuButton : Button
    {
        public MenuButton()
        {
            this.Style = FindResource("MenuButton") as Style;
        }
        public MenuButton(string caption, ICommand command)
        : this()
    {
        SetValue(ContentProperty, caption);
        this.command = command;
    }
}

在一个窗口中我添加了一个控件

<c:MenuButtons x:Name="MenuProject" c:MenuItems="{x:Static d:MenuItems.Project}" />

其中c:en d:是我的命名空间。 MenuItems是usercontrol MenuButtons的依赖项属性,在类中声明:

public readonly static MenuButton[] Project = new MenuButton[] { new MenuButton("Open", new Command()), ..etc };

资源定义如下:

 <Style x:Key="MenuButton"
           BasedOn="{StaticResource {x:Static ToolBar.ButtonStyleKey}}"
           TargetType="{x:Type c:MenuButton}">

视觉工作室设计师说:'MenuButton'TargetType与元素'MenuButton'的类型不匹配。代码运行正常,但设计人员无法调用我的MenuButton类的构造函数。在注释掉该行时,错误消失,但随后不应用样式,反之亦然。

1 个答案:

答案 0 :(得分:1)

this.Style = FindResource("MenuButton") as Style;不应出现在构造函数中。

您可以在OnApplyTemplate方法

中应用它
public overrride OnApplyTemplate()
{
     this.Style = FindResource("MenuButton") as Style;
     base.OnApplyTemplate(); 
}

希望这有帮助