wpf左侧菜单点击后一直改变背景色
时间: 2023-09-15 15:24:39 浏览: 68
要实现WPF左侧菜单点击后一直改变背景色,可以使用样式和触发器来实现。以下是一个简单的示例:
首先,创建一个样式来定义左侧菜单项的外观和行为:
```xaml
<Style x:Key="MenuItemStyle" TargetType="MenuItem">
<Setter Property="Background" Value="Transparent" />
<Setter Property="Foreground" Value="Black" />
<Setter Property="Padding" Value="10,5" />
<Setter Property="HorizontalAlignment" Value="Stretch" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="MenuItem">
<Grid>
<Border x:Name="BackgroundBorder" Background="{TemplateBinding Background}" />
<ContentPresenter Content="{TemplateBinding Header}" />
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsHighlighted" Value="True">
<Setter TargetName="BackgroundBorder" Property="Background" Value="LightBlue" />
<Setter Property="Foreground" Value="White" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
```
然后,在左侧菜单中应用这个样式:
```xaml
<Menu>
<MenuItem Header="菜单项1" Style="{StaticResource MenuItemStyle}" />
<MenuItem Header="菜单项2" Style="{StaticResource MenuItemStyle}" />
<MenuItem Header="菜单项3" Style="{StaticResource MenuItemStyle}" />
</Menu>
```
这样,当左侧菜单项被点击时,背景色会变为"LightBlue",并且文字颜色会变为白色。你可以根据需要修改样式中的颜色和其他属性来适应你的应用程序。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)