我的WPF应用程序(MVVM模式)上有一个按钮,它响应点击事件。基本上,如果单击此按钮,其背景将变为LightGreen(默认颜色为LightGray)。我已经使用以下代码实现了所需的行为:
<Button Grid.Column="2" Grid.Row="6" Grid.ColumnSpan="3" Grid.RowSpan="2" Content="{Binding FirstSchedule.Message}" Command="{Binding FirstScheduleButtonClick}">
<Button.Style>
<Style TargetType="Button">
<Setter Property="Background" Value="LightGray"></Setter>
<Style.Triggers>
<DataTrigger Binding="{Binding FirstScheduleButtonSelected}" Value="True">
<Setter Property="Background" Value="LightGreen"></Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
其中FirstScheduleButtonSelected
是由:
private bool _firstScheduleButtonSelected;
public bool FirstScheduleButtonSelected
{
get { return _firstScheduleButtonSelected; }
set { _firstScheduleButtonSelected = value; NotifyPropertyChanged("FirstScheduleButtonSelected"); NotifyPropertyChanged("Background"); }
}
现在我需要将此按钮的边框四舍五入。我已经尝试了这个解决方案How to create/make rounded corner buttons in WPF?,最后我得到了:
<Button Grid.Column="2" Grid.Row="6" Grid.ColumnSpan="3" Grid.RowSpan="2" Content="{Binding FirstSchedule.Message}" Command="{Binding FirstScheduleButtonClick}">
<Button.Style>
<Style TargetType="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border CornerRadius="15" Background="LightGray" BorderThickness="1" Padding="2">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="Background" Value="LightGray"></Setter>
<Style.Triggers>
<DataTrigger Binding="{Binding FirstScheduleButtonSelected}" Value="True">
<Setter Property="Background" Value="LightGreen"></Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
现在我的边框实际上是圆形的,但是当我点击按钮时它不会变为绿色。
问:我如何修改此按钮以使其边框四舍五入并保持我在点击时更改其颜色的功能?
答案 0 :(得分:1)
这就是我要做的事情:
<Window.Resources>
<!-- ... -->
<Style x:Key="GreenToggleButtonStyle" TargetType="ToggleButton">
<Setter Property="Background" Value="LightGray" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ToggleButton">
<Border
CornerRadius="15"
Background="{TemplateBinding Background}"
BorderThickness="1"
Padding="2"
>
<ContentPresenter
HorizontalAlignment="Center"
VerticalAlignment="Center"
/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsChecked" Value="True">
<Setter
Property="Background"
Value="LightGreen"
/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- ... -->
</Window.Resources>
...
<ToggleButton
Grid.Column="2"
Grid.Row="6"
Grid.ColumnSpan="3"
Grid.RowSpan="2"
Content="{Binding FirstSchedule.Message}"
IsChecked="{Binding FirstScheduleButtonSelected}"
Style="{StaticResource GreenToggleButtonStyle}"
/>