我在Wpf C#应用程序中使用按钮。 我已经为这些按钮声明了一种样式:
<Style x:Key="ButtonStyle" TargetType="{x:Type Button}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Grid Margin="0" Width="100" Height="60" >
//some more code here that sets color and stuff
<ContentPresenter HorizontalAlignment="Stretch" />
<Image Source="Images/search_48.png" / >
//some more code here (triggers)
</Setter.Value>
</Setter>
</Style>
我希望将此样式应用于窗口中的所有按钮,但图像不同。
我可以通过复制代码并将每个按钮设置为自己的样式来创建许多样式,同时仅更改图像,但我不希望这种情况发生。
我设置了这样的按钮样式:
<Button x:Name="buttonName"
Style="{DynamicResource ButtonStyle}"
Content="button text">
正如我所提到的,我有很多这样的按钮,我希望它们都具有相同的风格,但是为每个按钮改变这种风格的图像源。
有没有办法在不为每个按钮创建不同名称的相同样式的情况下执行此操作?
答案 0 :(得分:3)
为什么不将图像放在按钮内而不是样式中。
<Button x:Name="buttonName" Style="{DynamicResource ButtonStyle}" >
<Image Source="Images/search_48.png" / >
</Button>
风格将如下所示:
<Style x:Key="ButtonStyle" TargetType="{x:Type Button}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Grid Margin="0" Width="100" Height="60" >
//some more code here that sets color and stuff
<ContentPresenter HorizontalAlignment="Stretch" />
//some more code here (triggers)
</Setter.Value>
</Setter>
</Style>
更新:如果您有文字和图片,请使用堆叠面板:
<Button x:Name="buttonName" Style="{DynamicResource ButtonStyle}" >
<StackPanel Orientation="Horizontal">
<Image Source="Images/search_48.png" Stretch="None" />
<TextBlock>text</TextBlock>
</StackPanel>
</Button>
使用堆栈面板可以使用垂直或水平方向作为按钮布局。然后可以使用按钮内的边距定位文本和图像。