C#WPF动态按钮样式,具有基于x:name或x:key的不同图片
我想做一个像摇摇晃晃的游戏。我被主菜单卡住了,我已经像往常一样把东西复杂化了。我做了一个网格布局,我会把按钮放在那里,但每个按钮都是一张图片我使用ImageBrush来创建每个按钮的图片 我想为每个按钮创建一种样式,以便他们根据自己拥有的C#WPF动态按钮样式,具有基于x:name或x:key的不同图片,c#,wpf,button,dynamic,styles,C#,Wpf,Button,Dynamic,Styles,我想做一个像摇摇晃晃的游戏。我被主菜单卡住了,我已经像往常一样把东西复杂化了。我做了一个网格布局,我会把按钮放在那里,但每个按钮都是一张图片我使用ImageBrush来创建每个按钮的图片 我想为每个按钮创建一种样式,以便他们根据自己拥有的x:Name或x:Key更改背景。因此,一个带有x:Name或x:Key“PlayGame”的按钮会发现它与PlayGame.png、PlayGame\u Hover、PlayGame\u OnClick一样,其中“PlayGame”是一个变量。 换句话说,我希
x:Name
或x:Key
更改背景。因此,一个带有x:Name
或x:Key
“PlayGame”的按钮会发现它与PlayGame.png、PlayGame\u Hover
、PlayGame\u OnClick
一样,其中“PlayGame”是一个变量。
换句话说,我希望有一种样式可以过滤按钮的x:name或x:key,并在以后将其用作变量,这样我就可以做到:{StaticResource VARIABLENAME}
我现在的代码是:
<ImageBrush x:Key="PlayGame">
<ImageBrush.ImageSource>
<BitmapImage UriSource="./Pictures/PlayGameButton.png"/>
</ImageBrush.ImageSource>
</ImageBrush>
<ImageBrush x:Key="PlayGame_Hover">
<ImageBrush.ImageSource>
<BitmapImage UriSource="./Pictures/PlayGameButton_Hover.png"/>
</ImageBrush.ImageSource>
</ImageBrush>
<ImageBrush x:Key="PlayGame_OnClick">
<ImageBrush.ImageSource>
<BitmapImage UriSource="./Pictures/PlayGameButton_OnClick.png"/>
</ImageBrush.ImageSource>
</ImageBrush>
<Style TargetType="{x:Type Button}">
<Setter Property="Background" Value="{StaticResource PlayGame}" />
<Setter Property="FontSize" Value="15" />
<Setter Property="SnapsToDevicePixels" Value="True" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border CornerRadius="4" Background="{TemplateBinding Background}">
<Grid>
<ContentPresenter x:Name="MyContentPresenter" Content="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,0,0,0" />
</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="{StaticResource PlayGame_Hover}" />
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter Property="Background" Value="{StaticResource PlayGame_OnClick}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
我找到了一个不是很有效的解决方案,但不是我真正想要的 你可以给这种风格一个简单的解释 x:Key=“styleKey” 你必须给按钮这个部分: Style=“{StaticResource styleKey}”
这样你就必须为你想要的每一个不同的按钮做一个样式,但它会起作用,如果效率不是关键,你会很高兴的。:D你没有解释你的代码到底出了什么问题,请解释为什么无效,或者你会想到什么。我的问题是我不知道如何过滤按钮的x:名称,如果以后将其作为变量使用,那么1样式可能会使每个按钮的样式无效,因为这样您就必须为每个想要的按钮创建样式,我实际上已经记下了该样式。@Gr3gYx如果您有问题的答案,请将其作为答案发布,而不是作为问题的编辑。