C# 如何在不覆盖Mahapps主题的情况下设置属性?

C# 如何在不覆盖Mahapps主题的情况下设置属性?,c#,wpf,visual-studio,microsoft-metro,resourcedictionary,C#,Wpf,Visual Studio,Microsoft Metro,Resourcedictionary,我将Mahapps用于GUI,但是我想设置一些不同于可视属性的属性,例如边距和垂直对齐,因此我将其添加到用户控件.参考资料部分 <Style x:Key="{x:Type TextBox}" TargetType="TextBox" BasedOn="{StaticResource ResourceKey={x:Type TextBox}}"> <Setter Property="Margin" Value="2"/> <Setter Prope

我将Mahapps用于GUI,但是我想设置一些不同于可视属性的属性,例如
边距
垂直对齐
,因此我将其添加到
用户控件.参考资料
部分

<Style x:Key="{x:Type TextBox}" TargetType="TextBox" BasedOn="{StaticResource ResourceKey={x:Type TextBox}}">
     <Setter Property="Margin" Value="2"/>
     <Setter Property="VerticalAlignment" Value="Center"/>
</Style> 

但是,它会覆盖文本框的所有视觉样式属性,如何在不覆盖所有视觉样式设置的情况下添加这些属性?

为样式设置一个键

<Style x:Key="myCustomTextBoxStyle"
       TargetType="TextBox"
       BasedOn="{StaticResource ResourceKey={x:Type TextBox}}">
  <Setter Property="Margin" Value="2"/>
  <Setter Property="VerticalAlignment" Value="Center"/>
</Style>

在你需要的地方使用它

<TextBox Style={StaticResource myCustomTextBoxStyle} />

编辑 或者将其放入用户控件的主资源字典或没有键的窗口资源

<Window.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>

        </ResourceDictionary.MergedDictionaries>

        <Style TargetType="TextBox"
               BasedOn="{StaticResource ResourceKey={x:Type TextBox}}">
          <Setter Property="Margin" Value="2"/>
          <Setter Property="VerticalAlignment" Value="Center"/>
        </Style>
    </ResourceDictionary>
</Window.Resources>


希望这有帮助

它将影响所有的
文本框
,原因很简单,您定义的
键通常针对所有
文本框
。相反,为
键指定一个普通名称,如
Key=“specificttextbox”
。然后在您的xaml定义中为
文本框
指出这个样式。非常感谢您的回答,但是我想避免为我所使用的每个组件设置样式use@user2005494您可以在不使用键的情况下创建样式,并将其放在承载控件的主资源字典中