我对WPF有点缺乏经验,并试图在WPF中为一个带有图像图标的按钮获取一个简单的模板,以及工作文本。
样式代码:
<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>
显示按钮外的图像,“Test!”也是如此,但按钮内没有图像。
我做错了什么?
答案 0 :(得分: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>