在WPF XAML中禁用样式?

San*_*sal 27 c# wpf xaml styles

无论如何以程序方式关闭一个样式?

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

<Style TargetType="{x:Type TextBox}">
Run Code Online (Sandbox Code Playgroud)

我想添加一些代码来实际停止使用的样式元素,所以基本上恢复到默认的控件样式.

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

反正有没有这样做?

谢谢

工作方案

在WPF中切换主题

lox*_*xxy 63

要将样式设置为默认值,

在XAMl中使用,

<TextBox Style="{x:Null}" />
Run Code Online (Sandbox Code Playgroud)

在C#中使用,

myTextBox.Style = null;
Run Code Online (Sandbox Code Playgroud)

如果需要将样式设置为多个资源的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);
}
Run Code Online (Sandbox Code Playgroud)


Cod*_*ked 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>
Run Code Online (Sandbox Code Playgroud)

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

this.grid.Resources.Add(typeof(TextBox), new Style() { TargetType = typeof(TextBox) });
Run Code Online (Sandbox Code Playgroud)