Button template with image and text in wpf

后端 未结 7 838
刺人心
刺人心 2020-12-06 00:59

I want to create buttons with images and text inside. For example, i would use different images and text for buttons like \'Browse folders\' and \'Import\'.

One of th

相关标签:
7条回答
  • 2020-12-06 01:41
        <Button>
            <StackPanel Orientation="Horizontal">
                <Image Source="Resources/add.png" Stretch="None" />
                <TextBlock Margin="5,0,0,0">Add</TextBlock>
            </StackPanel>
        </Button>
    
    0 讨论(0)
  • 2020-12-06 01:50

    It doesn't have to be that complicated. Something as simple as putting a StackPanel inside a button will do the trick:

    <Button>
      <StackPanel>
        <TextBlock>My text here</TextBlock>
        <Image Source="some.jpg" Stretch="None" />
      </StackPanel>
    </Button>
    

    Then you can configure the StackPanel to control where the text should appear, alignment, etc.

    0 讨论(0)
  • 2020-12-06 02:00
    <Button x:Name="MyCoolButton"Width="200" Height="75">
    <Grid >
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Image Source="Pete-Brown-Silverlight-in-Action.png" Margin="5" Grid.Column="0" />
        <StackPanel Grid.Column="1" Margin="5">
            <TextBlock Text="Buy My Book!" FontWeight="Bold" />
            <TextBlock Text="Pete is writing THE Silverlight 4 book" TextWrapping="Wrap" />
        </StackPanel>
    </Grid>
    

    0 讨论(0)
  • 2020-12-06 02:00

    For me the IconButton of the XCeed WPF Toolkit (freeware) does the trick.

    0 讨论(0)
  • 2020-12-06 02:03

    No. What would you bind the Image.Source to? You need a DependencyProperty for this. Of course, you could also define a normal class which contains two properties: Text and ImageSource or Uri, and then use a DataTemplate to render instances of this class, but that would be even more code to write, and it is a little "smelly".

    What is the reason you do not want to use a dependency property or a custom class?

    0 讨论(0)
  • 2020-12-06 02:05

    Added Stretch="Uniform" to Sean's answer to address case if the image is originally larger than the button size (issue BrainSlugs83 mentioned in his comments that I ran into as well). More details of Stretch options at MSDN.

    <Button>
        <StackPanel Orientation="Horizontal">
            <Image Source="/ApplicationName;component/Images/MyImage.ico" Stretch="Uniform"/>
            <Label Padding="0">My Button Text</Label>
        </StackPanel>
    </Button>
    

    Wanted to add this as a comment to the answer under BrainSlugs83 but can't yet due to lack of points and was rejected from editing Sean's answer.

    0 讨论(0)
提交回复
热议问题