[WPF] 为Style 里的button添加鼠标点击响应事件

一个TabControl, 用的是PagedTabControl style, 在style中有个button, button在style里已经写了click事件,但是现在还需要加上一段功能,就是在响应事件之前对界面作一下判断。该怎么办呢?先看代码:

1. 控件XAML部分代码(位于文件form_loadatorigin.xaml):

        <!-- Form Body -->
        <TabControl x:Name="formLoadUnload"
            Style="{StaticResource PagedTabControl}"
            Tag="" HorizontalAlignment="Stretch"
            Grid.Row="0" Grid.RowSpan="2"
            Grid.IsSharedSizeScope="True"
            >

            <!-- Page 1 -->
            <TabItem Name="LoadUnloadPage1" Foreground="Black">
                <!-- 此处为Page1页面 略去-->
            </TabItem>

            <!-- Page 2 -->
            <TabItem Name="LoadUnloadPage2" Foreground="Black">
                <!-- 此处为Page2页面 略去-->
            </TabItem>
        </TabControl>

2. Style PagedTabControl代码:

<Style x:Key="PagedTabControl" TargetType="{x:Type TabControl}">
        <Setter Property="OverridesDefaultStyle" Value="True" />
        <Setter Property="SnapsToDevicePixels" Value="True" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type TabControl}">
                    <Grid KeyboardNavigation.TabNavigation="Local">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="Auto"/>
                        </Grid.ColumnDefinitions>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="Auto"/>
                            <RowDefinition Height="*"/>
                        </Grid.RowDefinitions>
                        <TabPanel Name="PagedHeaderPanel"
                            Grid.Row="0"
                            Grid.ColumnSpan="2"
                            Panel.ZIndex="0"
                            Margin="2,0,4,0"
                            KeyboardNavigation.TabIndex="1"
                                  />
                        <StackPanel Grid.Column="1" Grid.Row="0" Orientation="Horizontal" Panel.ZIndex="1" Margin="0,0,50,0"
                                    KeyboardNavigation.TabIndex="1">
                            <Button x:Name="PreviousPageButton"
                                        Grid.Column="0"
                                        Background="White">
                                <Button.Content>
                                    <Image Source="/Common.WPF.Assets;component/Images/btn_left.png"/>
                                </Button.Content>
                                <Button.Style>
                                    <Style BasedOn="{StaticResource RoundButtonStyle}" TargetType="{x:Type Button}">
                                        <Style.Triggers>
                                            <DataTrigger Binding="{Binding RelativeSource={RelativeSource TemplatedParent},Path=SelectedIndex}" Value="0">
                                                <Setter Property="IsEnabled" Value="False"/>
                                            </DataTrigger>
                                        </Style.Triggers>
                                    </Style>
                                </Button.Style>
                                <Button.Triggers>
                                    <EventTrigger RoutedEvent="Button.Click">
                                        <BeginStoryboard>
                                            <Storyboard>
                                                <Int32Animation
                                                            Storyboard.Target="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=‘‘}"
                                                            Storyboard.TargetProperty="SelectedIndex"
                                                            By="-1" Duration="0:0:.1" />
                                            </Storyboard>
                                        </BeginStoryboard>
                                    </EventTrigger>
                                </Button.Triggers>
                            </Button>
                            <TextBlock VerticalAlignment="Center" Margin="10,0,10,0" Style="{StaticResource NormalText19Style}" HorizontalAlignment="Center" TextAlignment="Center" >
                                <TextBlock.Text>
                                    <MultiBinding StringFormat="{}{0} {1} of {2}">
                                        <Binding RelativeSource="{RelativeSource TemplatedParent}" Path="Tag"/>
                                        <Binding RelativeSource="{RelativeSource TemplatedParent}" Path="SelectedIndex" Converter="{StaticResource ZeroBasedIndexConverter}"/>
                                        <Binding RelativeSource="{RelativeSource TemplatedParent}" Path="Items.Count"/>
                                    </MultiBinding>
                                </TextBlock.Text>
                            </TextBlock>
                            <Button x:Name="NextPageButton"
                                        Background="White">
                                <Button.Content>
                                    <Image Source="/Common.WPF.Assets;component/Images/btn_right.png"/>
                                </Button.Content>

                                <Button.Style>
                                    <Style BasedOn="{StaticResource RoundButtonStyle}" TargetType="{x:Type Button}">
                                        <Style.Triggers>
                                            <DataTrigger Binding="{Binding RelativeSource={RelativeSource TemplatedParent},Path=SelectedIndex}" Value="Items.Count">
                                                <Setter Property="IsEnabled" Value="False"/>
                                            </DataTrigger>
                                        </Style.Triggers>
                                    </Style>
                                </Button.Style>
                                <Button.Triggers>

                                    <EventTrigger RoutedEvent="Button.Click">
                                        <BeginStoryboard>
                                            <Storyboard>
                                                <Int32Animation
                                                            Storyboard.Target="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=‘‘}"
                                                            Storyboard.TargetProperty="SelectedIndex"
                                                            By="1" Duration="0:0:.1" />
                                            </Storyboard>
                                        </BeginStoryboard>
                                    </EventTrigger>
                                </Button.Triggers>
                            </Button>
                        </StackPanel>
                        <TabPanel
                                    Name="HeaderPanel"
                                    Grid.Row="0"
                                    Panel.ZIndex="1"
                                    Height="0"
                                    IsItemsHost="True">
                        </TabPanel>
                        <Border
                                    Name="Border"
                                    Grid.Row="1"
                                    Grid.ColumnSpan="2"
                                    BorderThickness="1"
                                    CornerRadius="2"
                                    KeyboardNavigation.TabNavigation="Local"
                                    KeyboardNavigation.DirectionalNavigation="Contained"
                                    KeyboardNavigation.TabIndex="2">
                            <ContentPresenter
                                        Name="PART_SelectedContentHost"
                                        Margin="4"
                                        ContentSource="SelectedContent" />
                        </Border>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

我们需要NextPageButton添加鼠标点击,下面就是在控件的实现文件里添加的代码:

3. 在form_loadatorigin.xaml.cs文件里的实现代码:

public form_loadatorigin()
{
    InitializeComponent();

    this.Loaded += new RoutedEventHandler(form_loadatorigin_Loaded);
}

private void form_loadatorigin_Loaded(object sender, RoutedEventArgs e)
{
    if (!IsFirstLoaded)
    {
        IsFirstLoaded = true;
        formLoadUnload.SelectionChanged += new SelectionChangedEventHandler(formLoadUnload_SelectionChanged);

        DependencyObject d1 = VisualTreeHelper.GetChild(formLoadUnload, 0);
        m_NextPageButton = LogicalTreeHelper.FindLogicalNode(d1, "NextPageButton") as Button;
        m_NextPageButton.PreviewMouseLeftButtonDown += new MouseButtonEventHandler(m_NextPageButton_PreviewMouseLeftButtonDown);
    }
}

void m_NextPageButton_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    e.Handled = true;
    if (ValidateAndShowErrors())
    {
        m_NextPageButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent, m_NextPageButton));
    }
}

private Button m_NextPageButton;
private bool IsFirstLoaded = false;        

注意:

1. m_NextPageButton必须为成员变量,如果改成局部变量,则添加事件不会起作用。至于原因,还没有找到为什么。

2. 此为抛砖引玉之技法,如有更好的方法,还望高手不吝赐教!

时间: 2024-11-02 12:11:29

[WPF] 为Style 里的button添加鼠标点击响应事件的相关文章

Qt窗口添加鼠标移动拖拽事件

1. .h文件中添加 private:    QPoint dragPosition; 2. 在cpp文件中重写鼠标点击和拖拽函数 void ShapeWidget::mousePressEvent(QMouseEvent * event){    if (event->button() == Qt::LeftButton) //点击左边鼠标    {         dragPosition = event->globalPos() - frameGeometry().topLeft(); 

cocos2dx 3.x(定时器或延时动作自动调用button的点击响应事件)实现自动内测

1 // 2 // ATTGamePoker.hpp 3 // MalaGame 4 // 5 // Created by work on 2016/11/09. 6 // 7 // 8 9 #ifndef ATTGamePoker_hpp 10 #define ATTGamePoker_hpp 11 12 #include <stdio.h> 13 #include <cocos2d.h> 14 15 16 class ATTGamePoker : public cocos2d:

WPF之路二 button添加背景图片点击后图片闪烁问题

在为button添加背景图片的时候,点击后发现图片闪烁,我们仔细观察,其实Button不仅仅只是在点击后会闪烁,在其通过点击或按Tab键获得焦点后都会闪烁,而通过点击其他按钮或通过按Tab键让Button失去焦点后就不闪烁了.如此我们可以推测出这不是点击或其他什么的问题而是焦点的问题,那么我们只要设置Button的Focusable属性为False就行了. 网上给的答案是要在button属性设置Focusable="False" ,无奈找属性栏里没有找到Focusable,于是在代码里

WPF 样式(Style)初体验 (一) 作用域

刚刚接触WPF的开发,顿时对样式设计产生了兴趣.因为之前对CSS比较感兴趣,不难发现WPF的Style和CSS的模式很类似.下面我就根据自己初步的理解和CSS样式表对比做下总结,有理解不正确的地方还希望各位前辈指正. (1)全局样式控制 影响的是整个项目的样式,我们可以在App.xaml文件里定义全局的样式(这里就类似于我们在一个web的项目中添加一个全局的CSS文件,然后在每个页面引用CSS样式): <Application.Resources> <Style TargetType=&

WPF 中style文件的引用

原文:WPF 中style文件的引用 总结一下WPF中Style样式的引用方法: 一,内联样式: 直接设置控件的Height.Width.Foreground.HorizontalAlignment.VerticalAlignment等属性.以设置一个Botton控件的样式为例,如: 复制代码 <Grid x:Name="ContentPanel" > <Button Content="Button" Name="btnDemo"

UWP Button添加圆角阴影(二)

原文:UWP Button添加圆角阴影(二) 阴影 对于阴影呢,WindowsCommunityToolkit中已经有封装好的DropShadowPanel啦,只要引用Microsoft.Toolkit.Uwp.UI.Controls这个Nuget包就可以使用啦. 直接把阴影套在咱们的圆角Button外面呢,会出现圆角的Button映出直角的阴影的丑陋状况.对于这种情况肯定是有处理方式的. 看DropShadowPanel的源码,对Content的特殊类型做了处理.下面我详细的说下. Compo

对另一个布局文件里的Button按钮进行监听

布局文件里面的Button写上 onClick = “onClick”,然后在你当前Activity的onClick方法中根据Button的id来做相应的操作 android:id="@+id/single_file_download" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" androi

Unity 添加鼠标右键事件

把此类放到 Editor下使用就OK 1 using UnityEngine; 2 using System.Collections; 3 using System.Collections.Generic; 4 using UnityEditor; 5 6 /// <summary> 7 /// 添加鼠标右键事件 8 /// </summary> 9 [InitializeOnLoad] 10 [ExecuteInEditMode] 11 public static class A

WPF 中,动态创建Button,并使Button得样式按照自定义的Resource样式显示

第一步:自定义一个Button的样式 1.新建一个xaml文件,在其中自定义好自己的Resources 这个Resource 的根节点是 <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"></ResourceDictio