【发布时间】:2013-10-22 02:37:25
【问题描述】:
在 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: 和 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}">
Visual Studio 设计师说:“MenuButton”TargetType 与元素“MenuButton”的类型不匹配。代码运行良好,但设计者在调用 MenuButton 类的构造函数时遇到了麻烦。注释掉该行时,错误消失,但样式未应用,反之亦然。
【问题讨论】:
-
不确定它是否相关,但
this.Style = FindResource("MenuButton") as Style;不应该在构造函数中。您可以覆盖OnApplyTemplate()方法并将其应用到那里。 -
这有帮助!效果是在运行时而不是在设计时应用样式,至少没有错误。为什么构造函数中不允许使用样式?
-
查看 Jon 对我的 question 的回答。
标签: wpf styles code-behind