1
我需要將某些分組單選按鈕設置爲切換按鈕。要做到這一點,我已經申請了以下樣式的單選按鈕:樣式WPF單選按鈕作爲具有正確IsEnabled行爲的切換按鈕
Style="{StaticResource {x:Type ToggleButton}}"
這給我我想要的風格,但我注意到一個惱人的副作用。我需要能夠在禁用控件時更改所選按鈕。這與正常的單選按鈕按預期工作。但是,使用切換按鈕樣式的按鈕不再顯示其中一個按鈕被選中。
在下面的演示中,如果您反覆點擊'切換啓用'按鈕,您可以看到選中的按鈕在重新啓用時仍然高亮顯示。但是,如果在禁用時更改選定按鈕,然後重新啓用(單擊「啓用切換」,「更改值」,「啓用切換」),則兩個按鈕都不會突出顯示。
我想要實現:
- 保持儘可能接近的切換按鈕的樣式。
- 當一個選中的按鈕被禁用時,保持藍色背景,但不透明。
- 無論值是否已更改,在重新啓用按鈕時都具有標準ToggleButton樣式。
XAML:
<Window x:Class="ToggleButtonDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ToggleButtonDemo"
mc:Ignorable="d"
Title="MainWindow" Height="200" Width="200"
Name="demoWindow"
DataContext="{Binding ElementName=demoWindow}">
<StackPanel>
<GroupBox Header="Radio" IsEnabled="{Binding Enable}">
<StackPanel Orientation="Horizontal">
<RadioButton Name="radio1" Content="One" GroupName="RadioGroup" IsChecked="True"/>
<RadioButton Name="radio2" Content="Two" GroupName="RadioGroup"/>
</StackPanel>
</GroupBox>
<GroupBox Header="Toggle" IsEnabled="{Binding Enable}">
<StackPanel Orientation="Horizontal">
<RadioButton Name="toggle1" Content="One" GroupName="ToggleGroup" Style="{StaticResource {x:Type ToggleButton}}" IsChecked="True"/>
<RadioButton Name="toggle2" Content="Two" GroupName="ToggleGroup" Style="{StaticResource {x:Type ToggleButton}}"/>
</StackPanel>
</GroupBox>
<Button Name="toggle" Content="Toggle enabled" Click="toggle_Click"/>
<Button Name="changeValue" Content="Change value" Click="changeValue_Click"/>
</StackPanel>
</Window>
後面的代碼:
using System.ComponentModel;
using System.Windows;
namespace ToggleButtonDemo
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window, INotifyPropertyChanged
{
private bool mEnable = true;
public bool Enable
{
get
{
return mEnable;
}
set
{
mEnable = value;
OnPropertyChanged(nameof(Enable));
}
}
public MainWindow()
{
InitializeComponent();
}
public event PropertyChangedEventHandler PropertyChanged;
public virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private void toggle_Click(object sender, RoutedEventArgs e)
{
Enable = !Enable;
}
private void changeValue_Click(object sender, RoutedEventArgs e)
{
if (radio1.IsChecked == true)
{
radio2.IsChecked = true;
}
else if (radio2.IsChecked == true)
{
radio1.IsChecked = true;
}
if (toggle1.IsChecked == true)
{
toggle2.IsChecked = true;
}
else if (toggle2.IsChecked == true)
{
toggle1.IsChecked = true;
}
}
}
}
這是偉大的。它給了我我正在尋找的行爲。是否有可能實現這一點而不必重新定義這麼多的風格?我真的很想保留更多的標準ToggleButton風格。 – sclarke81
不,您必須重新定義整個模板。您無法僅覆蓋部分模板。但是,這是默認模板在Windows 10上的外觀,稍作修改即可。您可以通過在VS中或混合中的設計模式中右鍵單擊ToggleButton,將默認值複製到您的XAML標記中,然後選擇編輯模板 - >編輯副本,然後按照您的要求對其進行修改。 – mm8
謝謝,這讓我得到了我所需要的。 – sclarke81