如何删除ToolBar中按钮的重复代码

时间:2014-04-15 07:16:57

标签: wpf wpf-controls

在我的wpf窗口中有一个带有一些按钮的工具栏如下所示,我的问题是按钮似乎可以共享模板,因为它们的内容具有完全相同的结构,但图像源和TextBlock文本是不同,那么如何删除所有按钮的重复代码?或者我必须定义一个自定义控件来执行此操作?

<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>

1 个答案:

答案 0 :(得分:1)

试试这个

 <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"/>