Reusable Custom Content for Buttons

后端 未结 3 1622
无人及你
无人及你 2021-01-15 23:32

My user interface makes use of customized Buttons: They contain both an Image and a Label.

I customized a single Button

相关标签:
3条回答
  • 2021-01-15 23:38

    I would say Control template editing as the easiest option to do this. Try using the below control template for all your buttons.I assumed the Button.Content is always the Label and Button.Tag always the Image Source

         <ControlTemplate x:Key="ImageText_button" TargetType="{x:Type Button}">
            <Grid Background="Transparent">
                <Image Source="{TemplateBinding Tag}" Stretch="Fill"/>
                <TextBlock Text="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
            </Grid>
        </ControlTemplate>
    

    And all of your button XAML will be as below

    <Button Content="MyLabel" Tag="\Image\abc.png" Template="{DynamicResource ImageText_button}" />
    
    0 讨论(0)
  • 2021-01-15 23:40

    you could:

    1. Derive a class from button, add the two properties and overide the control template. using a usercontrol that contains the button you will be forced to do work arounds such as exposing the button as a property. (to attach commands, get the click event etc.)

    2. create your own straight class that has the two properties, and set it to be the buttons content, and create a data template for it, then the button stays as a straight button. If you want these properties to be set from the xaml, derive from control or something that allows dependency properties

    I would use the second approach, its simple, and quick.

    0 讨论(0)
  • 2021-01-15 23:42

    The easiest thing to do is create a UserControl for this:

    1. Create a UserControl
    2. Add a "ImageSource" dependency property to the UserControl class of type BitmapSource for the image
    3. Add a "Text" dependency property to the UserControl class of type string
    4. For your UserControl XAML, put the following XAML (simplified for brevity, you can change to suit your layout needs)

    XAML for UserControl:

    <UserControl DataContext="{Binding RelativeSource={RelativeSource Self}}" ...>
        <Button>
            <StackPanel Orientation="Horizontal">
               <Image Source="{Binding ImageSource}" />
               <TextBlock Text="{Binding Text}" />
            </StackPanel>
        </Button>
    </UserControl>
    

    Now you can reuse your user control wherever you want like so:

    <myNS:MyUserControl ImageSource="MyImages/Foo.png" Text="Click here!" />
    
    0 讨论(0)
提交回复
热议问题