[英]Setting button flat style programmatically
I want to give a button a flat style programmatically when certain conditions occur. 当某些条件发生时,我想以编程方式给按钮一个平面样式。
This question shows how I can set a style to a control programmatically, having already defined it in XAML. 这个问题展示了我如何以编程方式为控件设置样式,已经在XAML中定义了它。
This question shows that a flat button style already exists, so it is not necessary to create one in XAML. 此问题表明已存在平面按钮样式,因此无需在XAML中创建一个。
ToolBar.ButtonStyleKey
returns a ResourceKey
, and the corresponding style is not defined in my window (it's in ToolBar). ToolBar.ButtonStyleKey
返回一个ResourceKey
,并且我的窗口中没有定义相应的样式(它在ToolBar中)。 How do I use it in code to set the style programmatically? 如何在代码中使用它来以编程方式设置样式?
As an alternative, you can try this: 作为替代方案,您可以尝试这样做:
XAML
<Button Name="FlatButton" Width="100" Height="30" Content="Test" />
Code behind
private void Button_Click(object sender, RoutedEventArgs e)
{
FlatButton.Style = (Style)FindResource(ToolBar.ButtonStyleKey);
}
This is a workaround that works. 这是一种有效的解决方法。 Add a style based on
ToolBar.ButtonStyleKey
to Window.Resources
as follows: 将基于
ToolBar.ButtonStyleKey
的样式添加到Window.Resources
,如下所示:
<Window.Resources>
<Style x:Key="MyStyle" BasedOn="{StaticResource {x:Static ToolBar.ButtonStyleKey}}" TargetType="Button" />
</Window.Resources>
Then, in code, refer to it as per first link in this question: 然后,在代码中,根据此问题中的第一个链接引用它:
button.Style = this.Resources["MyStyle"] as Style;
I'd prefer to have a code-only solution (no XAML) for this, but this works just as well. 我更喜欢有一个仅代码解决方案(没有XAML),但这也适用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.