【发布时间】:2011-08-04 17:45:53
【问题描述】:
有没有以编程方式关闭样式?
例如,我有一个链接到所有文本框的样式
<Style TargetType="{x:Type TextBox}">
我想添加一些代码来真正停止正在使用的样式元素,所以基本上恢复到默认控件样式。
我需要一种方法来切换我的样式,这样我就可以通过 C# 代码在 Windows 默认样式和我的自定义样式之间切换。
有没有办法做到这一点?
谢谢
工作解决方案
【问题讨论】:
有没有以编程方式关闭样式?
例如,我有一个链接到所有文本框的样式
<Style TargetType="{x:Type TextBox}">
我想添加一些代码来真正停止正在使用的样式元素,所以基本上恢复到默认控件样式。
我需要一种方法来切换我的样式,这样我就可以通过 C# 代码在 Windows 默认样式和我的自定义样式之间切换。
有没有办法做到这一点?
谢谢
工作解决方案
【问题讨论】:
为了将样式设置为默认,
在 XAMl 使用中,
<TextBox Style="{x:Null}" />
在 C# 中使用,
myTextBox.Style = null;
如果需要为多个资源设置样式为 null,请参阅 CodeNaked 的 回复。
我觉得,所有其他信息都应该在您的问题中,而不是在 cmets 中。无论如何,在后面的代码中,我认为这就是您要实现的目标:
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);
}
【讨论】:
您可以注入一个空白样式,该样式将优先于您的其他样式。像这样:
<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 中的 TextBox。您甚至可以通过编程方式将其添加到 Grid 中,例如:
this.grid.Resources.Add(typeof(TextBox), new Style() { TargetType = typeof(TextBox) });
【讨论】:
我知道答案已被接受,但我想添加我的解决方案,该解决方案在以下情况下效果很好:
在用户控制根目录下设置资源:
<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>
这成功地将主应用程序样式应用到
【讨论】:
在 Xaml 中,您可以通过显式设置样式来覆盖它。在代码隐藏中,您也可以显式设置样式。
<TextBox Style="{StaticResource SomeOtherStyle}"/>
myTextBox.Style = Application.Resources["SomeOtherStyle"];
【讨论】: