开发者

different images for enable and disable states of a button in WPF

开发者 https://www.devze.com 2022-12-08 02:29 出处:网络
I want to change the image of the button in the code below based on its state i.e. use different image for enable and disable state.开发者_如何学C

I want to change the image of the button in the code below based on its state i.e. use different image for enable and disable state.

开发者_如何学C
<Button CommandParameter="Open" >
    <StackPanel Orientation="Horizontal" >
        <Image Source="../icons/big/open.png" Width="20" Height="20"></Image>
    </StackPanel>
</Button>

Thank you.


You can use a style with triggers like this:

<Style TargetType="{x:Type Button}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <StackPanel Orientation="Horizontal" >
                    <Image Name="PART_Image" Source="path to normal image" />
                </StackPanel>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="Source" Value="path to mouse over image" TargetName="PART_Image"/>
                    </Trigger>
                    <Trigger Property="IsPressed" Value="True">
                        <Setter Property="Source" Value="path to pressed image" TargetName="PART_Image"/>
                    </Trigger>
                    <Trigger Property="IsEnabled" Value="False">
                        <Setter Property="Source" Value="path to disabled image" TargetName="PART_Image"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>


I used the following code to make images inside buttons to have half the opacity when the button is disabled and it works great!

<Style TargetType="Button">
    <Style.Resources>
        <Style TargetType="Image">
            <Style.Triggers>
                <Trigger Property="IsEnabled" Value="False">
                    <Setter Property="Opacity" Value="0.5" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </Style.Resources>
</Style>


Try using Style.Triggers see post wpf-style-trigger


Basically, create a style for the button which makes it display an image object in its content property, and then have a trigger which checks the buttons enabled state, and when it is TRUE have it be one image, and at all other times be the other image.

0

精彩评论

暂无评论...
验证码 换一张
取 消