我有一个用Style
写的自定义按钮XAML
。这是一个带图像和文字的按钮。
但Image
应该可以自定义。我需要更改设计器中的Source
属性。
我的代码:
<Window.Resources>
<ResourceDictionary>
<Style x:Key="SSbutton" TargetType="{x:Type Button}">
<Setter Property="Cursor" Value="Hand"/>
<Setter Property="Background" Value="Green"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Viewbox Stretch="Uniform">
<Border Background="{TemplateBinding Background}" Width="{TemplateBinding Width}"
Height="{TemplateBinding Height}">
<StackPanel Orientation="Horizontal" HorizontalAlignment="Left" VerticalAlignment="Center">
<!--I want to change this Source property-->
<Image Source="img/desktop.png" Width="30" HorizontalAlignment="Left" />
<TextBlock Margin="3,0,0,0" HorizontalAlignment="Right" VerticalAlignment="Center"
Text="{TemplateBinding Content}" FontSize="{TemplateBinding FontSize}"/>
</StackPanel>
</Border>
</Viewbox>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="25"/>
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="90" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Border Grid.Column="0" Grid.Row="1" Background="LightGreen">
<StackPanel >
<Button Style="{StaticResource SSbutton}" Width="90" Height="30" Content="Desktop" FontSize="13"
Foreground="White"/>
</StackPanel>
</Border>
</Grid>
我该怎么做?
答案 0 :(得分:1)
使用任意模板绑定到方便的花花公子Tag
属性,重新回到属性中;
<Style x:Key="SSbutton" TargetType="{x:Type Button}">
<Setter Property="Cursor" Value="Hand"/>
<Setter Property="Background" Value="Green"/>
<!-- Set a default -->
<Setter Property="Tag" Value="img/desktop.png"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Viewbox Stretch="Uniform">
<Border Background="{TemplateBinding Background}" Width="{TemplateBinding Width}"
Height="{TemplateBinding Height}">
<StackPanel Orientation="Horizontal" HorizontalAlignment="Left" VerticalAlignment="Center">
<!--I want to change this Source property-->
<Image Source="{Binding Path=Tag, RelativeSource={RelativeSource TemplatedParent}}" Width="30" HorizontalAlignment="Left" />
<TextBlock Margin="3,0,0,0" HorizontalAlignment="Right" VerticalAlignment="Center"
Text="{TemplateBinding Content}" FontSize="{TemplateBinding FontSize}"/>
</StackPanel>
</Border>
</Viewbox>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
然后在实例;
<Button Style="{StaticResource SSbutton}"
Tag="Some/Other/Image.png"
Width="90" Height="30"
Content="Desktop"
FontSize="13" Foreground="White"/>
希望这会有所帮助,欢呼。
编辑:根据OP的评论更新以反映wpf中模板绑定的路径注意事项。