WPF:修改公共控件模板中元素的属性

时间:2013-08-17 07:30:48

标签: .net wpf controltemplate

我为ControlTemplate中的按钮设置了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元素的来源。我怎么能这样做?

1 个答案:

答案 0 :(得分: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

enter image description here