2

ControlTemplate在下面制作了一个 for 按钮Resources

<ControlTemplate x:Key="buttonCtrlTemp" TargetType="{x:Type Button}">
                    <DockPanel x:Name="dock">
                        <Image x:Name="btnImg" Height="16" Width="16" DockPanel.Dock="Left"/>
                        <TextBlock VerticalAlignment="Center" Text="{TemplateBinding Button.Content}"/>
                    </DockPanel>
                    <ControlTemplate.Triggers>
                        <Trigger Property="Button.IsMouseOver" Value="True">
                            <Setter TargetName="dock" Property="Background" Value="{StaticResource AppBlue}"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>

我从按钮中将其引用为

<Button Content="Login" Template="{StaticResource buttonCtrlTemp}"/>

但是,我想为不同的按钮设置不同的图像,因此需要一些方法来Image从按钮设置控件模板中元素的来源。我怎样才能做到这一点?

4

1 回答 1

1

Tag在这种情况下,您可以使用。例子:

Template

<Image x:Name="btnImg" Source="{TemplateBinding Tag}" Height="16" Width="16" DockPanel.Dock="Left" />

使用:

<!-- In Resources -->
<BitmapImage x:Key="MyFind" UriSource="/BlackFind.jpg" />

<Button Name="FindTestButton" Tag="{StaticResource MyFind}" Template="{StaticResource buttonCtrlTemp}" ... />

最好在模板中ContentPresenter使用TextBlock。因为这个控件负责显示控件的内容,这是他唯一的目标。因此,首先,它小于“重量”(几乎所有控件都有您的ContentPresenter),其次,内容可能是通用类型。完整示例:

<Window.Resources>
    <BitmapImage x:Key="MyFind" UriSource="/BlackFind.jpg" />
    <BitmapImage x:Key="MyAttach" UriSource="/attachment.png" />

    <ControlTemplate x:Key="buttonCtrlTemp" TargetType="{x:Type Button}">
        <DockPanel x:Name="dock" Background="{TemplateBinding Background}">
            <Image x:Name="btnImg" Source="{TemplateBinding Tag}" Height="16" Width="16" DockPanel.Dock="Left" />
            <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" RecognizesAccessKey="True" />
        </DockPanel>

        <ControlTemplate.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter TargetName="dock" Property="Background" Value="Gray" />
            </Trigger>
        </ControlTemplate.Triggers>
    </ControlTemplate>
</Window.Resources>

<Grid>
    <Button Name="FindTestButton" Width="100" Tag="{StaticResource MyFind}" Background="Gainsboro" Content="FindButton" Height="30" Template="{StaticResource buttonCtrlTemp}" />
    <Button Name="AttachTestButton" Width="100" Tag="{StaticResource MyAttach}" Background="Gainsboro" Content="AttachButton" Height="30" Template="{StaticResource buttonCtrlTemp}" Margin="0,80,0,0" />
</Grid>

Output

在此处输入图像描述

于 2013-08-17T10:11:13.053 回答