我创建了一个自定义Button继承的自定义IconButton类,并添加了一些依赖项属性以将图像放置在按钮文本的前面。
代码开始像这样:
public partial class IconButton : Button
{
// Dependency properties and other methods
}
它带有一个如下所示的XAML文件:
<Button x:Class="Unclassified.UI.IconButton" x:Name="_this" ...>
<Button.Template>
<ControlTemplate>
<Button
Padding="{TemplateBinding Padding}"
Style="{TemplateBinding Style}"
Focusable="{TemplateBinding Focusable}"
Command="{TemplateBinding Button.Command}">
<StackPanel ...>
<Image .../>
<ContentPresenter
Visibility="{Binding ContentVisibility, ElementName=_this}"
RecognizesAccessKey="True"
Content="{Binding Content, ElementName=_this}">
<ContentPresenter.Style>
...
</ContentPresenter.Style>
</ContentPresenter>
</StackPanel>
</Button>
</ControlTemplate>
</Button.Template>
</Button>
到目前为止效果很好。(但是,如果您知道一种更简单的方法来覆盖Button的内容而不更改整个模板并将Button放置在Button中,请告诉我。每次尝试时,Visual Studio 2010 SP1在关闭最终XML标签的那一刻立即崩溃)
现在,我添加了一些代码来修复WPF破坏了Windows 8的Aero2主题。这是一个单独的ResourceDictionary,它将覆盖各种默认样式:(基于此,通过此处)
<ResourceDictionary ...>
<Style TargetType="{x:Type Button}">
...
</Style>
</ResourceDictionary>
新的ResourceDictionary会在启动时添加到App.xaml.cs中的“应用程序资源”中:
protected override void OnStartup(StartupEventArgs args)
{
base.OnStartup(e);
// Fix WPF's dumb Aero2 theme if we're on Windows 8 or newer
if (OSInfo.IsWindows8OrNewer)
{
Resources.MergedDictionaries.Add(new ResourceDictionary
{
Source = new Uri("/Resources/RealWindows8.xaml", UriKind.RelativeOrAbsolute)
});
}
...
}
这对于我放置在XAML视图中的普通Button控件也很有效。(我仍在寻找一种方法来找出真正的Windows主题,而不是依靠版本号。)
但是我的IconButton控件没有考虑这些新的默认值,仍然基于WPF的内置Button样式,这是非常基本的。(它实际上是一个狭窄的矩形,没有Win32显示的所有详细信息和交互。)
我想我需要一种方法告诉我的IconButton,它应该重新评估基本样式并查看新添加的RealWindows8样式。我怎样才能做到这一点?
我找到了解决方案。有两种方法可以完成此操作。任一个都足够。
XAML方式:
将样式属性添加到派生的控件。这将新控件的样式显式预设为应用程序中定义为Button样式的任何样式。为此,StaticResource就足够了。如果在使用派生控件的位置指定了其他样式,则它将替换此初始值。
<Button Style="{StaticResource {x:Type Button}}" ...>
...
</Button>
代码(隐藏)方式:
在派生类的构造函数中调用SetResourceReference方法。
public IconButton()
{
// Use the same style as Button, also when it is overwritten by the application.
SetResourceReference(StyleProperty, typeof(Button));
...
}
我已经为我的IconButton以及派生的TabControl和TabItem类进行了测试。
(来源)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句