有没有办法以编程的方式关闭样式?例如,我有一个与所有文本框关联的样式。
<Style TargetType="{x:Type TextBox}">
我希望添加一些代码来停止使用样式元素,基本上恢复默认的控件样式。
我需要一种方法来在我的样式中进行切换,以便可以通过C#代码在Windows默认样式和自定义样式之间进行切换。
有没有什么方法可以做到这一点?
谢谢
可行方案
要将样式设置为默认值,
在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);
}
<style></style>
<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 中的文本框。你甚至可以通过编程方式将其添加到 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>
这将成功地将主应用程序样式应用于<ToolBar>内部的控件。
<TextBox Style="{StaticResource SomeOtherStyle}"/>
myTextBox.Style = Application.Resources["SomeOtherStyle"];