Question

In my wpf window there is a toolbar with some buttons as below, my question is that for the buttons it seems they can share a template because they have exactly the same structures for its content, but the image source and TextBlock text are different, so how to remove the duplicated codes for all the buttons? Or I must define a custom control to do this?

<ToolBar Name="CommonToolbar">
    <Button Name="DownloadButton" Margin="5,0,5,0" Width="Auto" Command="{Binding Path=DownloadCmd}" ToolTip="{x:Static resx:GeneralRes.DownloadToolbarTooltip}" ToolTipService.ShowOnDisabled="True">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="16"/>
                <RowDefinition />
            </Grid.RowDefinitions>
            <Image Grid.Row="0" Source="Resources/Download.png" />
            <TextBlock Grid.Row="1" Text="{x:Static resx:GeneralRes.DownloadToolbarCaption}" />
        </Grid>
    </Button>

    <Button Name="UploadButton" Margin="5,0,5,0" Width="Auto" Command="{Binding Path=UploadCmd}" ToolTip="{x:Static resx:GeneralRes.UploadToolbarTooltip}"  ToolTipService.ShowOnDisabled="True">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="16"/>
                <RowDefinition/>
            </Grid.RowDefinitions>
            <Image Grid.Row="0" Source="Resources/Upload.png"/>
            <TextBlock Grid.Row="1" Text="{x:Static resx:GeneralRes.UploadToolbarCaption}"/>
        </Grid>
    </Button>

    <Button Name="ManualButton" Margin="5,0,5,0" Width="Auto" ToolTip="{x:Static resx:GeneralRes.ManualToolbarTooltip}" >
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="16"/>
                <RowDefinition/>
            </Grid.RowDefinitions>
            <Image Grid.Row="0" Source="Resources/help manual.png"/>
            <TextBlock Grid.Row="1" Text="{x:Static resx:GeneralRes.ManualToolbarCaption}"/>
        </Grid>
    </Button>

</ToolBar>
Was it helpful?

Solution

Try this

 <Window.Resources>
    <DataTemplate x:Key="ButtonContenttemplate"  DataType="{x:Type Button}">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="16"/>
                <RowDefinition />
            </Grid.RowDefinitions>
            <Image Grid.Row="0" Source="{Binding Path=Tag,RelativeSource={RelativeSource AncestorType=Button}}" />
            <TextBlock Grid.Row="1" Text="{Binding Path=Content,RelativeSource={RelativeSource AncestorType=Button}}" />
        </Grid>
    </DataTemplate>
</Window.Resources>

<Button Name="DownloadButton" Tag="catalogscreen.png" Content="HEllo world" ContentTemplate="{StaticResource ButtonContenttemplate}" Margin="5,0,5,0"  ToolTipService.ShowOnDisabled="True"/>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top