WPF container to turn all child controls to read-only

前端 未结 1 1131
旧巷少年郎
旧巷少年郎 2021-02-02 13:06

I would like to have a WPF container (panel, user control, etc.) that exposes a property to turn all children to read-only if set. This should pretty much be like setting a pare

1条回答
  •  情深已故
    2021-02-02 14:03

    You may do this with an attached property that provides value inheritance:

    public class ReadOnlyPanel
    {
        public static readonly DependencyProperty IsReadOnlyProperty =
            DependencyProperty.RegisterAttached(
                "IsReadOnly", typeof(bool), typeof(ReadOnlyPanel),
                new FrameworkPropertyMetadata(false,
                    FrameworkPropertyMetadataOptions.Inherits, ReadOnlyPropertyChanged));
    
        public static bool GetIsReadOnly(DependencyObject o)
        {
            return (bool)o.GetValue(IsReadOnlyProperty);
        }
    
        public static void SetIsReadOnly(DependencyObject o, bool value)
        {
            o.SetValue(IsReadOnlyProperty, value);
        }
    
        private static void ReadOnlyPropertyChanged(
            DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            if (o is TextBox)
            {
                ((TextBox)o).IsReadOnly = (bool)e.NewValue;
            }
            // other types here
        }
    }
    

    You would use it in XAML like this:

    
        
        
    
    

    0 讨论(0)
提交回复
热议问题