在WPF XAML中禁用样式?

时间:2011-08-04 17:45:53

标签: c# wpf xaml styles

无论如何都要以编程方式关闭一个样式吗?

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

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

我想添加一些代码来实际停止使用的样式元素,所以基本上还原为默认的控件样式。

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

有没有这样做?

由于

工作解决方案

Switching between themes in WPF

4 个答案:

答案 0 :(得分:59)

将样式设置为默认值

在XAMl中使用,

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

在C#中使用,

myTextBox.Style = null;

如果需要为多个资源将样式设置为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);
}

答案 1 :(得分:20)

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

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

在上面的示例中,只有Grid的隐式样式才会应用于Grid中的TextBoxes。您甚至可以通过编程方式将其添加到网格中,例如:

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

答案 2 :(得分:3)

我知道答案已被接受,但我希望在以下场景中添加我的解决方案:

  • 使用mahapps.metro的一个主要应用程序
  • 从主应用程序导入的其他项目,没有引用mahapps.metro,它作为插件导入(在运行中加载编译的.dll)
  • 使用&lt;工具条&GT;将所有内容重新设置为null,因此mahapps.metro样式不会应用于工具栏内的项目。
  • usercontrol用于为主应用程序提供自定义控件。

在用户控制root中设置资源:

<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>

这成功地将主应用程序样式应用于&lt;内部的控件。工具条&GT;

答案 3 :(得分:1)

在Xaml中,您可以通过显式设置样式来覆盖它。在代码隐藏中,您还可以显式设置样式。

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

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