WPF A good way to make a view/edit control?

前端 未结 4 2089
挽巷
挽巷 2021-02-10 04:18

this is just a question to discuss - what is the best way to make a view/edit control in WPF? E.g. we have an entity object Person, that has some props (name, surname, address,

4条回答
  •  不知归路
    2021-02-10 04:43

    Automatic Lock class

    I wrote an "AutomaticLock" class that has an inherited attached "DoLock" property.

    Setting the "DoLock" property to true re-templates all TextBoxes ComboBoxes, CheckBoxes, etc to be TextBlocks, non-editable CheckBoxes,etc. My code is set up so that other attached property can specify arbitrary template to use in locked ("view") mode, controls that should never automatically lock, etc.

    Thus the same view can easily be used for both editing and viewing. Setting a single property changes it back and forth, and it is completely customizable because any control in the view can trigger on the "DoLock" property to change its appearance or behavior in arbitrary ways.

    Implementation code

    Here is the code:

    public class AutomaticLock : DependencyObject
    {
      Control _target;
      ControlTemplate _originalTemplate;
    
      // AutomaticLock.Enabled:  Set true on individual controls to enable locking functionality on that control
      public static bool GetEnabled(DependencyObject obj) { return (bool)obj.GetValue(EnabledProperty); }
      public static void SetEnabled(DependencyObject obj, bool value) { obj.SetValue(EnabledProperty, value); }
      public static readonly DependencyProperty EnabledProperty = DependencyProperty.RegisterAttached("Enabled", typeof(bool), typeof(AutomaticLock), new FrameworkPropertyMetadata
      {
        PropertyChangedCallback = OnLockingStateChanged,
      });
    
      // AutomaticLock.LockTemplate:  Set to a custom ControlTemplate to be used when control is locked
      public static ControlTemplate GetLockTemplate(DependencyObject obj) { return (ControlTemplate)obj.GetValue(LockTemplateProperty); }
      public static void SetLockTemplate(DependencyObject obj, ControlTemplate value) { obj.SetValue(LockTemplateProperty, value); }
      public static readonly DependencyProperty LockTemplateProperty = DependencyProperty.RegisterAttached("LockTemplate", typeof(ControlTemplate), typeof(AutomaticLock), new FrameworkPropertyMetadata
      {
        PropertyChangedCallback = OnLockingStateChanged,
      });
    
      // AutomaticLock.DoLock:  Set on container to cause all children with AutomaticLock.Enabled to lock
      public static bool GetDoLock(DependencyObject obj) { return (bool)obj.GetValue(DoLockProperty); }
      public static void SetDoLock(DependencyObject obj, bool value) { obj.SetValue(DoLockProperty, value); }
      public static readonly DependencyProperty DoLockProperty = DependencyProperty.RegisterAttached("DoLock", typeof(bool), typeof(ControlTemplate), new FrameworkPropertyMetadata
      {
        Inherits = true,
        PropertyChangedCallback = OnLockingStateChanged,
      });
    
      // CurrentLock:  Used internally to maintain lock state
      [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
      public static AutomaticLock GetCurrentLock(DependencyObject obj) { return (AutomaticLock)obj.GetValue(CurrentLockProperty); }
      public static void SetCurrentLock(DependencyObject obj, AutomaticLock value) { obj.SetValue(CurrentLockProperty, value); }
      public static readonly DependencyProperty CurrentLockProperty = DependencyProperty.RegisterAttached("CurrentLock", typeof(AutomaticLock), typeof(AutomaticLock));
    
    
      static void OnLockingStateChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
      {
        AutomaticLock current = GetCurrentLock(obj);
        bool shouldLock = GetDoLock(obj) && (GetEnabled(obj) || GetLockTemplate(obj)!=null);
        if(shouldLock && current==null)
        {
          if(!(obj is Control)) throw new InvalidOperationException("AutomaticLock can only be used on objects derived from Control");
          new AutomaticLock((Control)obj).Attach();
        }
        else if(!shouldLock && current!=null)
          current.Detach();
      }
    
      AutomaticLock(Control target)
      {
        _target = target;
      }
    
      void Attach()
      {
        _originalTemplate = _target.Template;
        _target.Template = GetLockTemplate(_target) ?? SelectDefaultLockTemplate();
        SetCurrentLock(_target, this);
      }
    
      void Detach()
      {
        _target.Template = _originalTemplate;
        _originalTemplate = null;
        SetCurrentLock(_target, null);
      }
    
      ControlTemplate SelectDefaultLockTemplate()
      {
        for(Type type = _target.GetType(); type!=typeof(object); type = type.BaseType)
        {
          ControlTemplate result =
            _target.TryFindResource(new ComponentResourceKey(type, "AutomaticLockTemplate")) as ControlTemplate ??
            _target.TryFindResource(new ComponentResourceKey(typeof(AutomaticLock), type.Name)) as ControlTemplate;
          if(result!=null) return result;
        }
        return null;
      }
    }
    

    This code will allow you to specify an automatic lock template on a control-by-control basis or it will allow you to use default templates defined either in the assembly containing the AutomaticLock class, in the assembly containing your custom control that the lock template applies to, in your local resources in your visual tree (including your application resources)

    How to define AutomaticLock templates

    Default templates for WPF standard controls are defined in the assembly containing the AutomaticLock class in a ResourceDictionary merged into Themes/Generic.xaml. For example, this template causes all TextBoxes to turn into TextBlocks when locked:

    
      
    
    

    Default templates for custom controls may be defined in the assembly containing the custom control in a ResourceDictionary mered into its Themes/Generic.xaml. The ComponentResourceKey is different in this case, for example:

    
        ...
    

    If an application wants to override the standard AutomaticLock template for a specific type, it can place an automatic lock template in its App.xaml, Window XAML, UserControl XAML, or in the ResourceDictionary of an individual control. In each case the ComponentResourceKey should be specified the same way as for custom controls:

    x:Key="{ComponentResourceKey ResourceId=AutomaticLockTemplate, TypeInTargetAssembly={x:Type prefix:MyType}}"
    

    Lastly, an automatic lock template can be applied to a single control by setting its AutomaticLock.LockTemplate property.

    How to use AutomaticLock in your UI

    To use automatic locking:

    1. Set AutomaticLock.Enabled="True" on any controls that should be automatically locked. This can be done in a style or directly on individual controls. It enables locking on the control but does not cause the control to actually lock.
    2. When you want to lock, set AutomaticLock.DoLock="True" on your top-level control (Window, view, UserControl, etc) whenever you want the automatic locking to actually happen. You can bind AutomaticLock.DoLock to a checkbox or menu item, or you can control it in code.

    Some tips on effectively switching between view and edit modes

    This AutomaticLock class is great for switching betwen view and edit modes even if they are significantly different. I have several different techniques for constructing my views to accomodate layout differences while editing. Some of them are:

    1. Make controls invisible during edit or view mode by setting either their Template or AutomaticLockTemplate to an empty template as the case may be. For example, suppose "Age" is at the top of your layout in view mode and at the bottom in edit mode. Add a TextBox for "Age" in both places. In the top one set Template to the empty template so it doesn't show in Edit mode. In the bottom one set AutomaticLockTemplate to the empty template. Now only one will be visible at a time.

    2. Use a ContentControl to replace borders, layout panels, buttons, etc surrounding content without affecting the content. The ContentControl's Template has the surrounding borders, panels, buttons, etc for edit mode. It also has an AutomaticLockTemplate that has the view mode version.

    3. Use a Control to replace a rectangular section of your view. (By this I actually mean an object of class "Control", not a subclass therof.) Again, you put your edit mode version in the Template and your view mode version in the AutomaticLockTemplate.

    4. Use a Grid with extra Auto-sized rows and columns. Use a trigger on the AutomaticLock.DoLock property to update the Row, Column, RowSpan, and ColumnSpan properties of the items within the Grid. For example you could move a panel containing an "Age" control to the top by changing its Grid.Row from 6 to 0.

    5. Trigger on DoLock to apply a LayoutTranform or RenderTransform to your items, or to set other properties like Width and Height. This is useful if you want things to be bigger in edit mode, or if you want to make a TextBox wider and move the button beside it over against the edge.

    Note that you can use option #3 (a Control object with separate templates for edit and view modes) for the entire view. This would be done if the edit and view modes were completely different. In this case AutomaticLock still gives you the convenience of being able to set the two templates manually. It would look like this:

    
      
        
          
        
      
      
        
          
        
      
    
    

    Generally it is easier to tweak a few little positions and things between the edit and view modes, and better for your user experience because the user will have consistent layout, but if you do need a complete replacement AutomaticLock gives you that power as well.

提交回复
热议问题