WPF中具有不同高亮图像的多个ToggleButton图像

时间:2010-04-20 14:31:00

标签: wpf image xaml togglebutton

我是WPF的新手,需要一些指示,说明为什么这样做不正常。

我正在尝试制作一个最大化按钮,单击该按钮将更改为恢复按钮。我认为一个具有2种不同风格的切换按钮可以在后面的代码中进行更改。我首先尝试使最大化按钮工作并遇到问题。我收到错误'System.Windows.Controls.Image'不是Setter上'System.Windows.Controls.Image.Source'属性的有效值。在我的xaml。我似乎完全不了解某些事情。任何帮助都是最有帮助的:)

赖安

<Style x:Key="Maximize" TargetType="{x:Type ToggleButton}">
            <Style.Resources>
                <Image x:Key="MaxButtonImg" Source="/Project;component/Images/maxbutton.png" />
                <Image x:Key="MaxButtonHighlight" Source="/Project;component/Images/maxbutton-highlight.png" />
            </Style.Resources>
            <Setter Property="ContentTemplate">
                <Setter.Value>
                    <Image>
                        <Image.Style>
                            <Style TargetType="{x:Type Image}">
                                <Setter Property="Source" Value="{DynamicResource MaxButtonImg}"/>
                                <Style.Triggers>
                                    <Trigger Property="IsMouseOver" Value="True">
                                        <Setter Property="Source" Value="{DynamicResource MaxButtonHighlight}"/>
                                    </Trigger>
                                </Style.Triggers>
                            </Style>
                        </Image.Style>
                    </Image>
                </Setter.Value>
            </Setter>
        </Style>


<ToggleButton Name="MaxButton" Width="31" Height="31" BorderThickness="0" Click="MaxButton_Click" Margin="0,0,10,0" Tag="Max" 
                      Style="{DynamicResource Maximize}" />

我的代码背后会做一些简单的事情:

private void MaxButton_Click(object sender, RoutedEventArgs e)
    {
        ToggleButton tg = (ToggleButton)sender;

        if ( tg.IsChecked == true) {
            tg.Style = (Style)FindResource("Restore");
            this.WindowState = WindowState.Maximized;

        } else {
            tg.Style = (Style)FindResource("Maximize");
            this.WindowState = WindowState.Normal;
        }
    }

1 个答案:

答案 0 :(得分:1)

您不想在鼠标悬停时更改图像。我将我的图像添加到项目中名为Images的文件夹中,并将图像上的构建操作设置为Resource。

<Window.Resources>

        <Image x:Key="minImage" Source="/Images/min.png" Height="16" Width="16" />
        <Image x:Key="maxImage" Source="/Images/max.png" Height="16" Width="16" />

        <Style TargetType="{x:Type ToggleButton}" x:Key="minMaxButtonStyle">
            <Setter Property="Content" Value="{DynamicResource minImage}" />
            <Style.Triggers>
                <Trigger Property="IsChecked" Value="True">
                    <Setter Property="Content" Value="{DynamicResource maxImage}" />
                </Trigger>
            </Style.Triggers>
        </Style>

    </Window.Resources>

    <StackPanel>

        <ToggleButton Style="{StaticResource minMaxButtonStyle}" />

    </StackPanel>

</Window>