简体   繁体   中英

Simple WPF Button Control Template with variable images?

I am still new to WPF (writing my first app with it), but basically I am wanting (or think I want) to create a control of somekind that has 3 images (idle, hover, onClick) but that I can change the images. So now I have:

                <Rectangle Height="29" Width="35" Margin="0,2,0,0"
                       HorizontalAlignment="Left" VerticalAlignment="Top" 
                       Name="BTN_OpenDeviceSettings" ToolTip="Open Device Settings"
                       Fill="{DynamicResource device_grid___open_grid}"
                       MouseEnter="BTN_OpenDeviceSettings_MouseEnter"
                       MouseLeave="BTN_OpenDeviceSettings_MouseLeave"
                       MouseLeftButtonDown="BTN_OpenDeviceSettings_MouseLeftButtonDown"
                       MouseLeftButtonUp="BTN_OpenDeviceSettings_MouseLeftButtonUp">
                </Rectangle>

And it works great. But I want to separate the graphics from the code, and to make this work I manually swap the fill image in my C# code. I have seen code like:

<Button Name="btnNext" Padding="15,3" HorizontalAlignment="Right" Click="OnButtonClick">
    <Image Width="90" Height="90">
        <Image.Style>
            <Style TargetType="Image">
                <Setter Property="Source" Value="/resources/a.png" />
                <Style.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="Source" Value="/resources/b.png" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Image.Style>
    </Image>
</Button>

So I think that is what I am wanting. But ideally, I am going to have many of these buttons, so can I create something so that I do this:

<MyButton>
  <Images idleImage="someimage.png" hoverImage="someOtherImage.png" clickImage="someOtherOtherImage.png" onCLick="some_cSharp_method_to_call" />
</MyButton>

First solution: you can create a control template(or style if you are planning to show only images within a button) for buttons which will declare what images will be used for overlapping/clicking/other operations. This style will be shared by all buttons you want because it will have a designated key.

Second solution: you can subclass button and declare 3 dependency properties for hover/idle/clicked images. Then again you will need some default template(or style if button only displays images) for your subclassed button which will use that dependency properties.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM