C# 全局按钮';s动态样式,每个按钮具有不同的图像
我正在Wpf C#应用程序中使用按钮。 我已经为这些按钮声明了一种样式:C# 全局按钮';s动态样式,每个按钮具有不同的图像,c#,wpf,button,coding-style,C#,Wpf,Button,Coding Style,我正在Wpf C#应用程序中使用按钮。 我已经为这些按钮声明了一种样式: <Style x:Key="ButtonStyle" TargetType="{x:Type Button}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type 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" />
<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">
<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}" >
<Image Source="Images/search_48.png" / >
</Button>
然后,样式将如下所示:
<Button x:Name="buttonName"
Style="{DynamicResource ButtonStyle}"
Content="button text">
<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>
文本
使用堆栈面板将允许您对按钮布局使用垂直或水平方向。然后,可以使用按钮内的边距定位文本和图像。它会给出一个错误“属性“内容”设置了多次”。即使它起作用,在样式中,也更容易将图像放置在我想要的位置(在网格上定位),这很奇怪。您是否正在使用按钮输入文本?是的,我正在使用Content=“asadfdaf”我没有看到它,我刷新了3次。你能确定它在那里吗?