2011-08-04 112 views
21

无论如何要以编程方式关闭样式吗?在WPF XAML中禁用样式?

举个例子,我有一个链接到所有文本框的样式

<Style TargetType="{x:Type TextBox}"> 

我想添加一些代码真正停止样式元素被使用,所以基本上恢复到默认控件样式。

我需要一种方法在我的样式中进行切换,因此我可以通过C#代码在Windows默认样式和自定义样式之间切换。

有没有办法做到这一点?

感谢

工作液

Switching between themes in WPF

回答

51

对于设置样式为默认值,

在XAML中使用,

<TextBox Style="{x:Null}" /> 

在C#中使用,

myTextBox.Style = null; 

如果款式需要设置为对于多个资源为空,请参阅CodeNaked的回应。


我觉得,所有的附加信息应该在你的问题中,而不是在评论中。不管怎么说,在后面的代码我觉得这是你想达到什么目的:

Style myStyle = (Style)Application.Current.Resources["myStyleName"]; 

public void SetDefaultStyle() 
{ 
    if(Application.Current.Resources.Contains(typeof(TextBox))) 
     Application.Current.Resources.Remove(typeof(TextBox)); 

    Application.Current.Resources.Add(typeof(TextBox),  
             new Style() { TargetType = typeof(TextBox) }); 
} 

public void SetCustomStyle() 
{ 
    if (Application.Current.Resources.Contains(typeof(TextBox))) 
     Application.Current.Resources.Remove(typeof(TextBox)); 

    Application.Current.Resources.Add(typeof(TextBox), 
             myStyle); 
} 
+0

如果我要更改所有文本框的样式,然后能够将其更改回st再次使用之前? –

+0

我不认为这符合我的需要。 atm我有一种针对所有文本框的风格。我希望能够将程序中的每个文本框都恢复为远离我设置的自定义样式,并将其设置为空,以便它可以返回到Windows默认值。还有C#代码将其更改回我的自定义样式。任何可能性?谢谢 –

+0

这是你正在做什么来测试你的应用程序的默认样式,或者它是为了在你的应用程序中实现'切换到默认样式'功能?如果正在测试,那么只需在XAML中设置空样式并稍后将其删除即可。 – loxxy

1

在XAML中,您可以通过显式设置样式覆盖。在代码隐藏中,您还可以明确设置样式。

<TextBox Style="{StaticResource SomeOtherStyle}"/> 

myTextBox.Style = Application.Resources["SomeOtherStyle"]; 
17

你可以注入一个空白的样式,将优先于你的其他方式。像这样:

<Window> 
    <Window.Resources> 
     <Style TargetType="TextBox"> 
      <Setter Property="Background" Value="Red" /> 
     </Style> 
    </Window.Resources> 
    <Grid> 
     <Grid.Resources> 
      <Style TargetType="TextBox" /> 
     </Grid.Resources> 
    </Grid> 
</Window> 

在上面的示例中,只有网格的隐式样式将应用于网格中的文本框。你甚至可以将其添加到网格编程,像:

this.grid.Resources.Add(typeof(TextBox), new Style() { TargetType = typeof(TextBox) }); 
+0

这个答案是肯定的。不行。 – GameAlchemist

3

我知道答案已被接受,但我想补充我的解决方案,它在以下情况下工作真棒:

  • 一主要应用使用mahapps.metro
  • 从主应用程序导入没有提到mahapps.metro额外的项目,则其作为使用工具栏<>重新风格插件(装载上飞编译的.dll)
  • 一切都为空,因此mahapps.metro样式不适用于工具栏内的项目。
  • usercontrol用于为主应用程序提供自定义控件。
在用户控制根

设置资源:

<UserControl.Resources> 
    <Style x:Key="ButtonStyle" TargetType="Button" BasedOn="{StaticResource {x:Type Button}}" /> 
    <Style x:Key="ComboBoxStyle" TargetType="ComboBox" BasedOn="{StaticResource {x:Type ComboBox}}" /> 
</UserControl.Resources> 

然后在工具栏码可以是以下

   <ToolBar> 
        Block Template: 
        <ComboBox Style="{StaticResource ComboBoxStyle}"/> 
        <Button Content="Generate!" Style="{StaticResource ButtonStyle}"/> 
       </ToolBar> 

此成功地应用于主应用样式到控制<内部工具栏>