A read-only CheckBox in C# WPF

后端 未结 11 2081
南方客
南方客 2020-12-06 04:37

I am having a tricky problem, I want some slightly unusual behaviour from a checkbox and can\'t seem to figure it out. Any suggestions would be most welcome. The behaviour I

11条回答
  •  我在风中等你
    2020-12-06 05:23

    This is the class I've written to do something similar, for similar reasons (still raises all the Click and Command events as normal, but does not alter the binding source by default and does not auto-toggle. Unfortunately it does still have the animated fade-in-out on click, which is a bit strange if the click-handling code doesn't end up changing IsChecked.

    public class OneWayCheckBox : CheckBox
    {
        private class CancelTwoWayMetadata : FrameworkPropertyMetadata
        {
            protected override void Merge(PropertyMetadata baseMetadata,
                                          DependencyProperty dp)
            {
                base.Merge(baseMetadata, dp);
    
                BindsTwoWayByDefault = false;
            }
        }
    
        static OneWayCheckBox()
        {
            // Remove BindsTwoWayByDefault
            IsCheckedProperty.OverrideMetadata(typeof(OneWayCheckBox),
                                               new CancelTwoWayMetadata());
        }
    
        protected override void OnToggle()
        {
            // Do nothing.
        }
    }
    

    Usage:

    
    

    (Note that the IsChecked binding is now one-way by default; you can declare it as TwoWay if you want, but that would defeat part of the point.)

提交回复
热议问题