[英]Override IsMouseOver and change background color based on logic in WPF Button
Goal To make the default behavior for a buttons background onMouseEnter be to do nothing, yet still allow for programatically changing the button background in the logic of the application. 目标要使onMouseEnter按钮背景的默认行为是什么都不做,但仍允许在应用程序逻辑中以编程方式更改按钮背景。
Multiple posts address overriding the default MouseOver behaviour: 多个帖子地址覆盖了默认的MouseOver行为:
ex: How do you disable MouseOver effects on a Button in WPF? 例如: 如何在WPF中禁用按钮上的MouseOver效果?
However, in my application I need to keep changing the background color, and setting the MouseOver background color as a Trigger overrides my changes. 但是,在我的应用程序中,我需要继续更改背景色,并将MouseOver背景色设置为Trigger会覆盖我的更改。
<Button Content="Start" Name="buttonStart" Style="{StaticResource mainButton}" PreviewMouseDown="buttonStart_MouseDown"/>
<Button Content="Stop" Name="buttonStop" Style="{StaticResource mainButton}" PreviewMouseDown="buttonStop_MouseDown"/>
Style in App.xaml
App.xaml
样式
<Style x:Key="mainButton" TargetType="{x:Type Button}">
<Setter Property="Width" Value="250"/>
<Setter Property="Height" Value="75"/>
<Setter Property="FontSize" Value="40"/>
<Setter Property="FontFamily" Value="Segoe UI Light"/>
<Setter Property="Foreground" Value="White"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border Name="Border" BorderThickness="1"
BorderBrush="#404040">
<ContentPresenter Margin="2"
HorizontalAlignment="Center"
VerticalAlignment="Center"
RecognizesAccessKey="True"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="true">
<Setter TargetName="Border"
Property="Background" Value="{x:Null}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Logic: 逻辑:
private void buttonStop_MouseDown(object sender, RoutedEventArgs e)
{
//Change background colors for buttonStop and buttonStart
}
private void buttonStart_MouseDown(object sender, RoutedEventArgs e)
{
//Change background colors for buttonStop and buttonStart
}
How do I make the background on buttons do nothing onMouseEnter, yet still change the background in the code? 如何使按钮上的背景在onMouseEnter上不执行任何操作,但仍在代码中更改背景?
If you cannot remove the Trigger you could use a TextBlock for the content on your button then set the background of the TextBlock OnClick in your code behind. 如果无法删除触发器,则可以对按钮上的内容使用TextBlock,然后在后面的代码中设置TextBlock OnClick的背景。 You would have to adjust the style to allow for the TextBlock to fill the Button for it to appear correct. 您将不得不调整样式,以允许TextBlock填充Button,以使其正确显示。
Something like this: 像这样:
private void buttonStop_MouseDown(object sender, RoutedEventArgs e)
{
//Change background colors for buttonStop and buttonStart
TextBlock tb = new TextBlock();
tb.Background = Brushes.Blue;
((Button)sender).Content = tb;
}
...... ......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.