如何在不设置 IsEnabled 的情况下防止 ToggleButton 被切换 [英] How can I prevent a ToggleButton from being Toggled without setting IsEnabled

查看:35
本文介绍了如何在不设置 IsEnabled 的情况下防止 ToggleButton 被切换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ToggleButtons 列表被用作 ListBox 中的 ItemTemplate,类似于 this answer 使用 MultiSelect 模式列表框.但是,我需要确保始终选择至少一项.

I have a list of ToggleButtons being used as the ItemTemplate in a ListBox similar to this answer using the MultiSelect mode of the Listbox. However I need to make sure at least one item is always selected.

我可以通过在 ListBox.SelectionChanged 事件上将一个项目重新添加到 ListBox 的 SelectedItems 集合中来从 ListBox 获得正确的行为,但我的 ToggleButton 仍然移出其切换状态,所以我认为我需要在早期停止它过程.

I can get the proper behavior from the ListBox by just adding an item back into the ListBox's SelectedItems collection on the ListBox.SelectionChanged event but my ToggleButton still moves out of its toggled state so I think I need to stop it earlier in the process.

我不想在最后一个 Selected 按钮上设置 IsEnabled="False" ,因为我更喜欢保留 Enabled 视觉样式而不必重做我的按钮模板.有什么想法吗?

I would like to do it without setting IsEnabled="False" on the last button Selected because I'd prefer to stay with the Enabled visual style without having to redo my button templates. Any ideas?

推荐答案

您可以覆盖 OnToggle 方法以防止切换状态,而不是调用基本实现:

You can override the OnToggle method to prevent toggling the state, by not calling the base implementation :

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));
}

这篇关于如何在不设置 IsEnabled 的情况下防止 ToggleButton 被切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆