问题描述
|
我的WPF应用程序中的菜单按钮很少。
这种情况类似于网站中的菜单。
当我单击一个按钮时,我希望该按钮样式与其他按钮样式不同,而当我选择另一个按钮样式时,上一个按钮应该是正常样式,并且所选样式应应用于此所选按钮。
您能告诉我如何通过ControlTemplate实现此功能,还是必须维护一个IsSelected属性,让我们知道选择了哪个按钮?
谢谢,
VJ
解决方法
您可以尝试使用RadionButton。下面的示例将为RadioButton创建一个Flat按钮外观。
<Window x:Class=\"WpfApplication8.Window1\"
xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"
xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"
Title=\"Window1\" Height=\"300\" Width=\"472\">
<Window.Resources>
<Style TargetType=\"{x:Type RadioButton}\">
<Setter Property=\"Focusable\"
Value=\"False\" />
<Setter Property=\"GroupName\"
Value=\"filter\" />
<Setter Property=\"IsTabStop\"
Value=\"False\" />
<Setter Property=\"VerticalAlignment\"
Value=\"Center\" />
<Setter Property=\"HorizontalAlignment\"
Value=\"Center\" />
<Setter Property=\"Template\">
<Setter.Value>
<ControlTemplate TargetType=\"{x:Type RadioButton}\">
<ControlTemplate.Resources>
<Style TargetType=\"{x:Type TextBlock}\">
<Setter Property=\"VerticalAlignment\"
Value=\"Center\" />
<Setter Property=\"HorizontalAlignment\"
Value=\"Center\" />
</Style>
</ControlTemplate.Resources>
<Border x:Name=\"PART_border\"
CornerRadius=\"2\"
Margin=\"2\"
Background=\"Transparent\"
BorderThickness=\"1\"
BorderBrush=\"{x:Static SystemColors.ControlDarkBrush}\"
SnapsToDevicePixels=\"True\">
<StackPanel Orientation=\"Horizontal\"
HorizontalAlignment=\"Center\" VerticalAlignment=\"Center\">
<ContentPresenter x:Name=\"PART_content\" />
</StackPanel>
</Border>
<ControlTemplate.Triggers>
<Trigger Property=\"IsChecked\"
Value=\"True\">
<Setter TargetName=\"PART_content\"
Property=\"TextBlock.FontWeight\"
Value=\"Bold\" />
<Setter TargetName=\"PART_border\"
Property=\"Background\">
<Setter.Value>
<LinearGradientBrush StartPoint=\"0,0\"
EndPoint=\"0,1\">
<GradientStop Color=\"Black\"
Offset=\"0\" />
<GradientStop Color=\"white\"
Offset=\"1\" />
</LinearGradientBrush>
</Setter.Value>
</Setter>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<StackPanel Orientation=\"Horizontal\" >
<RadioButton Height=\"30\" Width=\"100\" Content=\"First\"></RadioButton>
<RadioButton Height=\"30\"
Width=\"100\"
Content=\"Second\"></RadioButton>
<RadioButton Height=\"30\"
Width=\"100\"
Content=\"First\"></RadioButton>
</StackPanel>
</Grid>
用于带图像的RadioButton的内容,请查看Matt \的博客
http://madprops.org/blog/wpf-killed-the-radiobutton-star/
, 您应该使用内置的视觉状态处理并在XAML中创建状态/样式。
在您的具体情况下,看来您所追求的是一组RadioButton,因此您不必编写任何代码来处理状态之间的切换。
, 您最好为此使用自定义单选按钮列表。请查看以下文章。
不允许在列表框中取消选择/取消选择
您可以轻松地自定义选定和取消选定的样式以符合您的要求