2013-08-17 83 views
2

我在Resources如下製成的ControlTemplate爲按鈕:WPF:修改通用控制元件的屬性模板

<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

在這種情況下,您可以使用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