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

时间:2014-05-03 14:01:12

标签: c# wpf xaml

我有一个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" />

悬停,检查和取消选中时会显示正确的图像 但我注意到内容已经消失(“我的复选框”),而且我只想在没有选中时悬停状态出现,我该怎么做?

2 个答案:

答案 0 :(得分:19)

在WPF中,您通常会查找具有所需功能的控件,然后使其看起来像您想要的那样。因此,如果您需要CheckBox功能,则可以使用CheckBox控件并将其Template更改为您想要的内容。因此,您可以为将设置自定义Style

CheckBox创建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功能

答案 1 :(得分:1)

如果您覆盖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>