由于我正在使用MaterialDesign,我的自定义控件包含一个按钮,该按钮使用派生/默认的Material Design按钮。当将样式应用于此按钮时,Material Design样式会被覆盖以取代默认的wpf按钮。如何在保持基本的Material Design样式的情况下应用样式?
由于我的问题仅与将样式应用于按钮有关,因此我省略了搜索框样式,并创建了一个示例来说明我的问题,其中只包含一个按钮。 Generic.xaml-CustomButton
<Style TargetType="{x:Type local:CustomButton}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:CustomButton}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<!-- Normally the below button would be inside a grid with additional buttons, labels and content presenter. I have removed these for simplicity-->
<Button Name="MaterialButton"
Content="CustomButton">
<Button.Style>
<Style TargetType="{x:Type Button}" BasedOn="{StaticResource {x:Type Button}}">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Foreground" Value="Red"/>
</Trigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
App.xaml - (Material Design在资源字典中。)
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
我尝试过的方法
我尝试使用建议的BasedOn
属性这里和这里,但这并没有解决我的问题。
根据"Material Design theme is lost" FAQ中基于材料风格派生的结果会导致以下错误: 异常:找不到名为“MaterialDesignFlatButton”的资源。资源名称区分大小写。
Generic.Xaml 尝试更改 CustomButton
<!--Same custon control as before--->
<Button.Style>
<Style TargetType="{x:Type Button}" BasedOn="{StaticResource MaterialDesignFlatButton}">
<!--same trigger-->
<Style TargetType="local:CustomButton" BasedOn="{StaticResource MaterialDesignFlatButton}" />
。尝试这个样式。我会更新我的答案。 - BionicCodeResourceDictionary
中定义。一直以来,我都期望你在_App.xaml_中定义Style
。请尝试我的答案,并让我知道是否解决了你的问题。 - BionicCodeCustomButton
的Controltemplate
相当无意义。没有必要在按钮内部放置一个按钮。因此,我删除了这个多余的内部Button
。通常您会在模板中添加一个简单的ContentPresenter
。这个ContentPresenter
将自动绑定到ContentControl.Content
属性以呈现内容值。请检查并尝试我的最新更新。 - BionicCode