我有一个ToggleButtons列表,用作ListBox中的ItemTemplate,类似于使用Listbox的MultiSelect模式的此答案.但是我需要确保始终选择至少一个项目.
我可以通过在ListBox.SelectionChanged事件中向ListBox的SelectedItems集合中添加一个项来从ListBox中获取正确的行为,但是我的ToggleButton仍然会移出其切换状态,因此我认为我需要在此过程的早期停止它.
我想在没有在最后一个按钮上设置IsEnabled ="False"的情况下这样做,因为我更喜欢使用Enabled视觉样式,而不必重做我的按钮模板.有任何想法吗?
Tho*_*que 32
您可以OnToggle通过不调用基本实现来覆盖该方法以防止切换状态:
public class LockableToggleButton : ToggleButton
{
protected override void OnToggle()
{
if (!LockToggle)
{
base.OnToggle();
}
}
public bool LockToggle
{
get { return (bool)GetValue(LockToggleProperty); }
set { SetValue(LockToggleProperty, value); }
}
// Using a DependencyProperty as the backing store for LockToggle. This enables animation, styling, binding, etc...
public static readonly DependencyProperty LockToggleProperty =
DependencyProperty.Register("LockToggle", typeof(bool), typeof(LockableToggleButton), new UIPropertyMetadata(false));
}
Run Code Online (Sandbox Code Playgroud)
小智 7
您是否尝试过使用 RadioButtons 代替?通常不能在不选择另一个的情况下取消选择。它也可以设计为看起来像一个 ToggleButton:
<RadioButton Style="{StaticResource {x:Type ToggleButton}}"/>
Run Code Online (Sandbox Code Playgroud)
或者,如果你已经有了Style它,那就让它吧BasedOn="{x:Type ToggleButton}"。请注意,Visual Studio 编辑器在第一种情况下会显示错误,但它可以编译并正常工作。