tags:

views:

51

answers:

4

Hi, 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, phone etc.). One presentation of the control would be a read-only view. And the other would have the edit view for this same person. Example:

<UserControl x:Name="MyPersonEditor">
    <Grid>
        <Grid x:Name="ViewGrid" Visibility="Visible">
            <TextBlock Text="Name:"/>
            <TextBlock Text="{Binding Person.Name}"/>
            <Button Content="Edit" Click="ButtonEditStart_Click"/>
        </Grid>

        <Grid x:Name="EditGrid" Visibility="Collapsed">
            <TextBlock Text="Name:"/>
            <TextBox Text="{Binding Person.Name}"/>
            <Button Content="Save" Click="ButtonEditEnd_Click"/>
        </Grid>
    </Grid>
</UserControl>

I hope that the idea is clear. The two options I see right now

  1. two grids with visibility switching and
  2. a TabControl without its header panel

This is just a discussion question - not much trouble with it, yet I am just wondering if there are any other possibilities and elegant solutions to this.

A: 

I would create a single View with 2 different configoptions , f.e. 2 different constructors to make the the relevant field editable/readonly or visible/hidden

This way you don't write redundant XAML and you can configurate all fields over code behind or ViewModel when using MVVM

KroaX
+1  A: 
<Grid>
    <TextBlock Text="Name:"/> 
    <LabelText="{Binding Person.Name}" Cursor="IBeam" MouseDoubleClick="lblName_dblClick"/>  <!-- set the IsEditMode to true inside this event -->
    <TextBox Text="{Binding Person.Name}" Visibility="{Binding IsEditMode, Converter={StaticResource BoolToVisConverter}}"/>
    <Button Content="OK" Click="btnSave_Click" Visibility="{Binding IsEditMode, Converter={StaticResource BoolToVisConverter}}"/> <!-- set the IsEditMode to false inside this event -->
</Grid>

Use a command rather, if you're familiar with.

Veer
I have a very similar solution at the moment, but with changing panels that depend on the IsEditMode property. Quite similar mechanism of work (just on different level of elements).Anyway, the reason for my question here is that this method brings a ton of XAML with it (e.g. all controls' visibility has to be bound; in my case there are only two bindings for two tabs, but that means that I have to replicate all of the controls in the second tab).And that makes the code a bit less readable... yet again, is it a matter of taste how to do it. Thanks for the reply!
Jefim
A: 

Sounds like a job for a DataTemplateSelector to me. If you would rather switch the individual controls in place I would do something similar to what Veer suggested.

Bryan Anderson
+1  A: 

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:

<ControlTemplate TargetType="{x:Type TextBox}"
  x:Key="{ComponentResourceKey ResourceId=TextBox, TypeInTargetAssembly={x:Type lc:AutomaticLock}}">
  <TextBlock Text="{TemplateBinding Text}" />
</ControlTemplate>

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:

<ControlTemplate TargetType="{x:Type prefix:MyType}"
  x:Key="{ComponentResourceKey ResourceId=AutomaticLockTemplate, TypeInTargetAssembly={x:Type prefix:MyType}}">
    ...

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:

<Control>
  <Control.Template>
    <ControlTemplate>
      <!-- Edit mode view here -->
    </ControlTemplate>
  </Control.Template>
  <lib:AutomaticLock.LockTemplate>
    <ControlTemplate>
      <!-- View mode view here -->
    </ControlTemplate>
  </lib:AutomaticLock.LockTemplate>
</Control>

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.

Ray Burns
Any possibility of sharing an example of your AutomaticLock Class?
Metro Smurf
No problem. Here it is.
Ray Burns
This code looks great :)One minus could be that it is impossible to restructure the view/edit (e.g. if we need the "view" mode to be different from "edit" mode). But that is not the problem of the solution as it is not made for this purpose. I will definitely give this a try in my project!
Jefim
It is true that AutomaticLock provides the maximum value when your view and edit modes layouts are similar to each other, but when using the AutomaticLock class it is **not impossible to restructure the UI when switching between view and edit modes. In fact, it is extremely easy.** I've extended my answer to explain the some of the techniques I use for handling layout changes between modes and how they leverage AutomaticLock.
Ray Burns