2013-05-02 79 views
0

我對WPF有點沒有經驗,並試圖在WPF中獲得一個簡單的模板,用於帶有圖標圖標的按鈕以及工作的文本。將BitmapImage作爲標籤傳遞給DataTemplate

樣式代碼:

<Style x:Key="DatabaseButtonWithImageTag" TargetType="Button" BasedOn="{StaticResource DatabaseButton}"> 
    <Setter Property="ContentTemplate"> 
     <Setter.Value> 
      <DataTemplate> 
       <Grid> 
        <Grid.ColumnDefinitions> 
         <ColumnDefinition Width="1*" /> 
         <ColumnDefinition Width="2*" /> 
        </Grid.ColumnDefinitions> 

        <Image Grid.Column="0" Width="100" Source="{TemplateBinding Tag}" /> 
        <ContentControl Grid.Column="1" Content="{TemplateBinding Content}" /> 
       </Grid> 
      </DataTemplate> 
     </Setter.Value> 
    </Setter> 
</Style> 

查看代碼:

 <Image Source="{StaticResource image_new_patient}"/> 
    <Button Style="{StaticResource DatabaseButtonWithImageTag}" Tag="{StaticResource image_new_patient}" Width="150" Height="100"> 
     Test! 
    </Button> 

的按鈕顯示之外的圖像,所以是 「測試!」,但按鈕內沒有圖像。

我在做什麼錯?

+0

[更改WPF按鈕背景圖像編程]的可能重複(http://stackoverflow.com/questions/15819796/change-wpf-button-背景圖像編程) – 2013-05-02 21:48:13

回答

0

TemplateBinding在DataTemplate中不起作用。

您可以使用此workaroud:

<Window.Resources> 
    <BitmapImage x:Key="image_new_patient" UriSource="bsp.jpg" /> 
    <local:ImageConverter x:Key="imageConverter" /> 
    <Style x:Key="DatabaseButtonWithImageTag" TargetType="Button"> 
     <Setter Property="ContentTemplate"> 
      <Setter.Value> 
       <DataTemplate> 
        <Grid> 
         <Grid.ColumnDefinitions> 
          <ColumnDefinition Width="1*" /> 
          <ColumnDefinition Width="2*" /> 
         </Grid.ColumnDefinitions> 

         <Image Grid.Column="0" Width="100" Source="{Binding RelativeSource={RelativeSource AncestorType=Button}, Path=Tag}" /> 

         <ContentControl Grid.Column="1" Content="{TemplateBinding Content}" /> 
        </Grid> 
       </DataTemplate> 
      </Setter.Value> 
     </Setter> 
    </Style> 

</Window.Resources> 
<StackPanel> 
    <Image Source="{StaticResource image_new_patient}" Width="50"/> 
    <Button Style="{StaticResource DatabaseButtonWithImageTag}" Tag="{StaticResource image_new_patient}" Width="150" Height="100"> 
     Test! 
    </Button> 

</StackPanel> 

+0

非常感謝,它的作品:) – Maverick 2013-05-03 11:46:31