如何为复选框图像创建自定义WPF XAML样式

本文关键字:自定义 WPF XAML 样式 创建 图像 复选框 | 更新日期: 2023-09-27 18:01:42

我有一个c# WPF页面,在它上面我放置了几个小图像,我想像复选框一样(我有我自己的悬停和选择状态的自定义图像)。

我正在手动更改图像,如:

<Image x:Name="Image_Custom" Source="/Images/checkcircle_off.png" Width="16" Height="16" HorizontalAlignment="Left"  Margin="30,107,0,0" VerticalAlignment="Top" MouseEnter="Image_Custom_MouseEnter" MouseLeave="Image_Custom_MouseLeave" MouseUp="Image_Custom_MouseUp" MouseLeftButtonDown="Image_Custom_MouseLeftButtonDown"/>

    private void Image_Custom_MouseEnter(object sender, MouseEventArgs e)
    {
        if (_selected == false)
        {
            var uriSource = new Uri("/Images/checkcircle_hover.png", UriKind.Relative);
            Image_Custom.Source = new BitmapImage(uriSource);
        }
    }
    private void Image_Custom_MouseLeave(object sender, MouseEventArgs e)
    {
        if (_selected == false)
        {
            var uriSource = new Uri("/Images/checkcircle_off.png", UriKind.Relative);
            Image_Custom.Source = new BitmapImage(uriSource);
        }
    }
    private void Image_Custom_MouseUp(object sender, MouseButtonEventArgs e)
    {
        if (_selected)
        {
            var uriSource = new Uri("/Images/checkcircle_off.png", UriKind.Relative);
            Image_Custom.Source = new BitmapImage(uriSource);
            _selected = false;
        }
        else
        {
            var uriSource = new Uri("/Images/checkcircle_on.png", UriKind.Relative);
            Image_Custom.Source = new BitmapImage(uriSource);
            _selected = true;
        }
    }
    private void Image_Custom_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        if (_selected)
        {
            var uriSource = new Uri("/Images/checkcircle_off.png", UriKind.Relative);
            Image_Custom.Source = new BitmapImage(uriSource);
            _selected = false;
        }
        else
        {
            var uriSource = new Uri("/Images/checkcircle_on.png", UriKind.Relative);
            Image_Custom.Source = new BitmapImage(uriSource);
            _selected = true;
        }
    }

这个可以工作,但是非常麻烦,我将有多达20个复选框。

我如何创建一个自定义的XAML样式,我可以使用每个图像或类似的东西。

编辑:

我使用了下面的样式来处理悬停:

<Page.Resources>
    <Style TargetType="Image" x:Key="checkBoxStyle">
        <Setter Property="Source" Value="/Images/checkcircle_off.png"/>
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter Property="Source" Value="/Images/checkcircle_hover.png"/>
            </Trigger>
        </Style.Triggers>
    </Style>
</Page.Resources>
    <Image x:Name="Image_Custom" Style="{StaticResource checkBoxStyle}" Width="16" Height="16" HorizontalAlignment="Left"  Margin="30,107,0,0" VerticalAlignment="Top" MouseEnter="Image_Custom_MouseEnter" MouseLeave="Image_Custom_MouseLeave" MouseUp="Image_Custom_MouseUp" MouseLeftButtonDown="Image_Custom_MouseLeftButtonDown"/>

但是我不知道如何处理点击事件。我该怎么做呢?

编辑2

我做了以下的事情:

        <Style TargetType="{x:Type CheckBox}" x:Key="myCheckBoxStyle">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type CheckBox}">
                    <Image x:Name="checkBoxImage" Source="/Images/checkcircle_off.png"></Image>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsChecked" Value="True">
                            <Setter TargetName="checkBoxImage" Property="Source" Value="/Images/checkcircle_on.png"/>
                        </Trigger>
                        <Trigger Property="IsChecked" Value="False">
                            <Setter TargetName="checkBoxImage" Property="Source" Value="/Images/checkcircle_off.png"/>
                        </Trigger>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter TargetName="checkBoxImage" Property="Source" Value="/Images/checkcircle_hover.png"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
<CheckBox Content="My CheckBox" Style="{StaticResource myCheckBoxStyle}" Width="16" Height="16" Foreground="white" FontSize="16" HorizontalAlignment="Left" Margin="30,242,0,0" VerticalAlignment="Top" />

正确的图像出现时,悬停,选中和未选中。
但我注意到,内容已经消失("我的复选框"),也我只希望悬停状态出现时,它没有被选中,我怎么能做到这一点?

如何为复选框图像创建自定义WPF XAML样式

在WPF中,您通常会寻找具有所需功能的控件,然后使其看起来像您想要的那样。所以如果你想要CheckBox的功能,那么你使用CheckBox控制,改变它的Template,使它成为你想要的。因此,您可以为CheckBox创建Style,这将设置自定义Template

<Window.Resources>
    <Style TargetType="{x:Type CheckBox}" x:Key="myCheckboxStyle">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type CheckBox}">
                    <StackPanel Orientation="Horizontal">
                        <Image x:Name="checkboxImage" Source="normal.png" Width="32"/>
                        <ContentPresenter/>
                    </StackPanel>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsChecked" Value="True">
                            <Setter TargetName="checkboxImage" Property="Source" Value="checked.png"/>
                        </Trigger>
                        <MultiTrigger>
                            <MultiTrigger.Conditions>
                                <Condition Property="IsMouseOver" Value="True"/>
                                <Condition Property="IsChecked" Value="False"/>
                            </MultiTrigger.Conditions>
                            <Setter TargetName="checkboxImage" Property="Source" Value="hover.png"/>
                        </MultiTrigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>
然后在任意CheckBox 上使用
<CheckBox Style="{StaticResource myCheckboxStyle}" Content="ABC"/>

,您将拥有所有CheckBox功能与您的自定义外观

如果你重写CheckBox并创建一个特定的样式,它将看起来像这样:

public class MyCheckBox : CheckBox
{
    #region ImageNormal
    /// <summary>
    /// ImageNormal Dependency Property
    /// </summary>
    public static readonly DependencyProperty ImageNormalProperty =
        DependencyProperty.Register("ImageNormal", typeof(ImageSource), typeof(MyCheckBox),
            new FrameworkPropertyMetadata((ImageSource)null));
    /// <summary>
    /// Gets or sets the ImageNormal property. This dependency property 
    /// indicates ....
    /// </summary>
    public ImageSource ImageNormal
    {
        get { return (ImageSource)GetValue(ImageNormalProperty); }
        set { SetValue(ImageNormalProperty, value); }
    }
    #endregion
    #region ImageChecked
    /// <summary>
    /// ImageChecked Dependency Property
    /// </summary>
    public static readonly DependencyProperty ImageCheckedProperty =
        DependencyProperty.Register("ImageChecked", typeof(ImageSource), typeof(MyCheckBox),
            new FrameworkPropertyMetadata((ImageSource)null));
    /// <summary>
    /// Gets or sets the ImageChecked property. This dependency property 
    /// indicates ....
    /// </summary>
    public ImageSource ImageChecked
    {
        get { return (ImageSource)GetValue(ImageCheckedProperty); }
        set { SetValue(ImageCheckedProperty, value); }
    }
    #endregion
    //... other image properties removed for simplicity
    static MyCheckBox()
    {
        //Override base class style
        DefaultStyleKeyProperty.OverrideMetadata(typeof(MyCheckBox), new FrameworkPropertyMetadata(typeof(MyCheckBox)));
    }

}

关联的XAML样式:

<Style TargetType="{x:Type local:MyCheckBox}">
    <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type CheckBox}">
                <Grid>
                    <VisualStateManager.VisualStateGroups>
                        <VisualStateGroup x:Name="CommonStates">
                            <VisualState x:Name="Normal"/>
                            <VisualState x:Name="MouseOver">
                                <Storyboard>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)" Storyboard.TargetName="grdNormal">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Collapsed}"/>
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)" Storyboard.TargetName="grdMouseOver">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Visible}"/>
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </VisualState>
                            <VisualState x:Name="Pressed">
                                <Storyboard>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)" Storyboard.TargetName="grdPressed">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Visible}"/>
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)" Storyboard.TargetName="grdNormal">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Collapsed}"/>
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </VisualState>
                            <VisualState x:Name="Disabled"/>
                        </VisualStateGroup>
                        <VisualStateGroup x:Name="CheckStates">
                            <VisualState x:Name="Checked">
                                <Storyboard>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)" Storyboard.TargetName="imgUnchecked1">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Collapsed}"/>
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)" Storyboard.TargetName="imgChecked1">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Visible}"/>
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)" Storyboard.TargetName="imgUnchecked2">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Collapsed}"/>
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)" Storyboard.TargetName="imgChecked2">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Visible}"/>
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)" Storyboard.TargetName="imgUnchecked3">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Collapsed}"/>
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)" Storyboard.TargetName="imgChecked3">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Visible}"/>
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </VisualState>
                            <VisualState x:Name="Unchecked"/>
                            <VisualState x:Name="Indeterminate"/>
                        </VisualStateGroup>
                    </VisualStateManager.VisualStateGroups>
                    <Grid x:Name="grdNormal">
                        <Image x:Name="imgUnchecked1" Source="{Binding ImageNormal, RelativeSource={RelativeSource TemplatedParent}}"/>
                        <Image x:Name="imgChecked1" Visibility="Collapsed" Source="{Binding ImageNormal, RelativeSource={RelativeSource TemplatedParent}}"/>
                    </Grid>
                    <Grid x:Name="grdMouseOver" Visibility="Collapsed">
                        <Image x:Name="imgUnchecked2" Source="{Binding ImageMouseOver, RelativeSource={RelativeSource TemplatedParent}}"/>
                        <Image x:Name="imgChecked2" Visibility="Collapsed" Source="{Binding ImageMouseOverChecked, RelativeSource={RelativeSource TemplatedParent}}"/>
                    </Grid>
                    <Grid x:Name="grdPressed" Visibility="Collapsed">
                        <Image x:Name="imgUnchecked3" Source="{Binding ImagePressed, RelativeSource={RelativeSource TemplatedParent}}"/>
                        <Image x:Name="imgChecked3" Visibility="Collapsed" Source="{Binding ImagePressedChecked, RelativeSource={RelativeSource TemplatedParent}}"/>
                    </Grid>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>