WPF 触发器例子

WPF的触发器很强大,这里简单附上触发器的一个小例子,分别用XMAL和CS代码来实现一个功能,鼠标悬停在button上时改变字体颜色

1.XMAL代码如下:

<Window x:Class="wpf触发器.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid Name="grid" >
        <Button x:Name="btnHello" Content="clickMe" Height="24" Width="60"  >
            <Button.Style>
                <Style TargetType="Button">
                    <Style.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="Foreground" Value="Blue"></Setter>
                            <Setter Property="Background" Value="#00ff00"></Setter>
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </Button.Style>
        </Button>
    </Grid>
</Window>


Cs代码如下:
        public MainWindow()
        {
            InitializeComponent();
            Button btn = new Button() { Width =100,Height=50,Content="overme"};

            //实例style,参数带上控件类型
            Style m_style = new Style( typeof(Button));

            //实例trigger,并加上触发的property和value
            Trigger trigger = new Trigger();
            trigger.Property = IsMouseOverProperty;
            trigger.Value = true;

            //当满足trigger设定的条件时,要应用的属性值
            trigger.Setters.Add(new Setter(ForegroundProperty, Brushes.Red));

            m_style.Triggers.Add(trigger);
            btn.Style = m_style;
            grid.Children.Add(btn); //grid就是外面的Grid
        }
   


posted @ 2016-09-25 12:12  birdhumen鸟人  阅读(368)  评论(1编辑  收藏  举报