【问题标题】:How to remove duplicated codes for buttons in a ToolBar如何删除工具栏中按钮的重复代码
【发布时间】:2014-04-15 16:28:07
【问题描述】:

在我的 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>

【问题讨论】:

    标签: wpf wpf-controls


    【解决方案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"/>
    

    【讨论】:

      猜你喜欢
      • 2019-09-10
      • 1970-01-01
      • 1970-01-01
      • 2020-03-28
      • 1970-01-01
      • 1970-01-01
      • 2019-07-31
      • 2017-05-06
      • 2017-03-08
      相关资源
      最近更新 更多