覆盖IsMouseOver并根据WPF Button

时间:2016-05-02 21:57:38

标签: c# wpf

目标 要使按钮背景onMouseEnter的默认行为是什么都不做,但仍然允许以编程方式更改应用程序逻辑中的按钮背景。

多个帖子地址覆盖默认的MouseOver行为:

ex:How do you disable MouseOver effects on a Button in WPF?

但是,在我的应用程序中,我需要不断更改背景颜色,并将MouseOver背景颜色设置为触发器会覆盖我的更改。

 <Button Content="Start" Name="buttonStart" Style="{StaticResource mainButton}" PreviewMouseDown="buttonStart_MouseDown"/>
 <Button Content="Stop" Name="buttonStop" Style="{StaticResource mainButton}" PreviewMouseDown="buttonStop_MouseDown"/>

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>

逻辑:

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

    }

如何让按钮上的背景在onMouseEnter上不执行任何操作,但仍会更改代码中的背景?

1 个答案:

答案 0 :(得分:1)

如果您无法删除触发器,则可以使用TextBlock作为按钮上的内容,然后在后面的代码中设置TextBlock OnClick的背景。您必须调整样式以允许TextBlock填充Button以使其显示正确。

这样的事情:

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;
}

...