c# - 全局按钮的动态样式,每个按钮都有不同的图像

标签 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}">
                    <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">

正如我提到的,我有很多这样的按钮,我希望它们都具有相同的样式,但要为每个按钮更改这种样式的图像源。

有没有办法在不为每个按钮创建具有不同名称的相同样式的情况下做到这一点?

最佳答案

为什么不直接将图像放在按钮内而不是放在样式中。

<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>

使用堆栈面板将允许您为按钮布局使用垂直或水平方向。然后可以使用按钮内的边距定位文本和图像。

关于c# - 全局按钮的动态样式,每个按钮都有不同的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8987054/

相关文章:

c# - LINQ to Entities 无法识别方法 'System.DateTime ToDateTime(System.String)' 方法

c# - 在同一个模拟实例上断言对公共(public)方法的调用

C# LINQ 查询

c# - 通过 RestSharp 发送非多部分数据

wpf - 工具栏按钮样式被忽略?

wpf - 嵌套列表框大小调整问题

c# - WPF MVVM - 从 ViewModel 访问 View 中 DataGrid 的 DependencyProperty

javascript - 如果文本字段值匹配,则单击时更改按钮图像源

java - Android Studio中如何保存按钮的状态?

jquery - jquery中按钮点击事件的问题