Posts mit dem Label AttachedProperty werden angezeigt. Alle Posts anzeigen
Posts mit dem Label AttachedProperty werden angezeigt. Alle Posts anzeigen

Freitag, 11. Mai 2012

Seting Visibility on a GridViewColum of a ListView in WPF

There are two different ways how the Visibility of a GridViewColumn can be set.

1. With attached properties
2. Extending the GridViewColumn

In the attached property version, we save the original width of the column in another attached property, whenever the visibility is set to something else than Visible. After that we set the Width to 0.
This way the column disappears.

When resetting the Visibility to visible, we retrieve the original saved width and restore it to the Width property again.

public class GridViewColumnVisibilityManager
{
    public static Visibility GetVisibility(DependencyObject o)
    {
        return (Visibility)o.GetValue(VisibilityProperty);
    }

    public static void SetVisibility(DependencyObject obj, Visibility value)
    {
        obj.SetValue(VisibilityProperty, value);
    }

    public static readonly DependencyProperty VisibilityProperty =
        DependencyProperty.RegisterAttached("Visibility", typeof(Visibility),
        typeof(GridViewColumnVisibilityManager),
        new FrameworkPropertyMetadata(Visibility.Visible, 
        FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
        new PropertyChangedCallback(OnVisibilityPropertyChanged)));

    private static void OnVisibilityPropertyChanged(DependencyObject d, 
                                     DependencyPropertyChangedEventArgs e)
    {
        var column = d as GridViewColumn;
        if (column != null)
        {
            var visibility = GetVisibility(column);
            if (visibility == Visibility.Visible)
            {
                // set the with back to the original
                column.Width = GetVisibleWidth(column);
            }
            else
            {
                // store the original width
                SetVisibleWidth(column, column.Width);
                // set the column width to 0 to hide it
                column.Width = 0.0;
            }
        }
    }

    public static double GetVisibleWidth(DependencyObject obj)
    {
        return (double)obj.GetValue(VisibleWidthProperty);
    }

    public static void SetVisibleWidth(DependencyObject obj, double value)
    {
        obj.SetValue(VisibleWidthProperty, value);
    }

    /// <summary>
    /// dpenendency property that stores the last visible width
    /// whenever the visibility changes this propert is used to set or get the width
    /// </summary>
    public static readonly DependencyProperty VisibleWidthProperty =
        DependencyProperty.RegisterAttached("VisibleWidth", 
                typeof(double), 
                typeof(GridViewColumnVisibilityManager), 
                new UIPropertyMetadata(double.NaN));

}

<ListView ItemsSource="{Binding DataObjects}" Grid.Column="1" >
    <ListView.View>
        <GridView>
            <GridView.Columns>
                <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}" 
                     foo:GridViewColumnVisibilityManager.Visibility="{Binding IsVisible, Converter={StaticResource boolToVis}}"/>
                <GridViewColumn Header="Vorname" DisplayMemberBinding="{Binding Vorname}"/>
            </GridView.Columns>
        </GridView>
    </ListView.View>
</ListView>


The extension works the same way except that we can use a variable to store the original width instead of an attached property.

public class GridViewColumnExt : GridViewColumn
{
    public Visibility Visibility
    {
        get
        {
            return (Visibility)GetValue(VisibilityProperty);
        }
        set
        {
            SetValue(VisibilityProperty, value);
        }
    }

    public static readonly DependencyProperty VisibilityProperty =
        DependencyProperty.Register("Visibility", typeof(Visibility), 
        typeof(GridViewColumnExt),
        new FrameworkPropertyMetadata(Visibility.Visible, 
        FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
        new PropertyChangedCallback(OnVisibilityPropertyChanged)));

    private static void OnVisibilityPropertyChanged(DependencyObject d, 
                                  DependencyPropertyChangedEventArgs e)
    {
        var column = d as GridViewColumnExt;
        if (column != null)
        {
            column.OnVisibilityChanged((Visibility)e.NewValue);
        }
    }

    private void OnVisibilityChanged(Visibility visibility)
    {
        if (visibility == Visibility.Visible)
        {
            Width = _visibleWidth;
        }
        else
        {
            _visibleWidth = Width;
            Width = 0.0;
        }
    }

    double _visibleWidth;
}

<ListView ItemsSource="{Binding DataObjects}" Grid.Column="1" >
    <ListView.View>
        <GridView>
            <GridView.Columns>
                <c:GridViewColumnExt Header="Name" DisplayMemberBinding="{Binding Name}" 
                     Visibility="{Binding IsVisible, Converter={StaticResource boolToVis}}"/>
                <GridViewColumn Header="Vorname" DisplayMemberBinding="{Binding Vorname}"/>
            </GridView.Columns>
        </GridView>
    </ListView.View>
</ListView>

Mittwoch, 11. Januar 2012

Simple Drag and Drop Handler using MVVM and Attached Properties

I wanted to implement some Drag & Drop behaviour to my ListBoxes. Because the Drag & Drop is handled through Events I created some Attached Properties that would handle these events and pass the needed information to my ViewModel through binding.

First I created an Interface that I could pass to the Attached Property that contained two Method definitions that would get executed when the DropEvent gets fired.
One method returnes a bool defining if the Drop can be executed.
The second method handles the DropEvent.
    public interface IDragDropHandler
    {
        bool CanDrop(IDataObject dropObject, IEnumerable dropTarget);

        void OnDrop(IDataObject dropObject, IEnumerable dropTarget);
    }

Then I created the DependencyProperty that gets attached. In the PropertyMetadata I created a new object containing the PropertyChangedHandler that gets executed when the dragDropHandlerProperty is changed. Inside the instance I hooked to the DragEvent of the DependencyObject and added a handler that gets executed when the DragEvent gets fired.
    public static class DragDropBehaviour
    {
        #region DragDropHandler

        #region DragDropHandler DependencyProperty

        /// 
        /// attached property that handles drag and drop
        /// 
        public static readonly DependencyProperty DragDropHandlerProperty =
           DependencyProperty.RegisterAttached("DragDropHandler", 
           typeof(IDragDropHandler), 
           typeof(DragDropBehaviour),
           new PropertyMetadata(null, new ExecuteDragDropBehaviour().PropertyChangedHandler));

        public static void SetDragDropHandler(DependencyObject o, object propertyValue)
        {
            o.SetValue(DragDropHandlerProperty, propertyValue);
        }
        public static object GetDragDropHandler(DependencyObject o)
        {
            return o.GetValue(DragDropHandlerProperty);
        }

        #endregion

        internal abstract class DragDropBehaviourBase
        {
            protected DependencyProperty _property;

            /// <summary>
            /// attach the events
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="oldValue"></param>
            /// <param name="newValue"></param>
            protected abstract void AdjustEventHandlers(DependencyObject sender, 
                                                        object oldValue, object newValue);

            /// <summary>
            /// Listens for a change in the DependencyProperty
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            public void PropertyChangedHandler(DependencyObject sender, 
                                               DependencyPropertyChangedEventArgs e)
            {
                if (_property == null)
                {
                    _property = e.Property;
                }

                object oldValue = e.OldValue;
                object newValue = e.NewValue;

                AdjustEventHandlers(sender, oldValue, newValue);
            }
        }

        /// <summary>
        /// an internal class to handle listening for the drop event and executing the dropaction
        /// </summary>
        private class ExecuteDragDropBehaviour : DragDropBehaviourBase
        {
            /// <summary>
            /// attach the events
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="oldValue"></param>
            /// <param name="newValue"></param>
            protected override void AdjustEventHandlers(DependencyObject sender, 
                                                   object oldValue, object newValue)
            {
                var element = sender as UIElement;
                if (element == null) { return; }

                if (oldValue != null)
                {
                    element.RemoveHandler(UIElement.DropEvent, 
                                          new DragEventHandler(ReceiveDrop));
                }

                if (newValue != null)
                {
                    element.AddHandler(UIElement.DropEvent, 
                                       new DragEventHandler(ReceiveDrop));
                }
            }

            /// <summary>
            /// eventhandler that gets executed when the DropEvent fires
            /// </summary>
            private void ReceiveDrop(object sender, DragEventArgs e)
            {
                var dp = sender as DependencyObject;
                if (dp == null)
                    return;

                var action = dp.GetValue(_property) as IDragDropHandler;
                if (action == null)
                    return;

                IEnumerable dropTarget = null;
                if (sender is ItemsControl)
                    dropTarget = (sender as ItemsControl).ItemsSource;

                if (action.CanDrop(e.Data, dropTarget))
                    action.OnDrop(e.Data, dropTarget);
                else
                    e.Handled = true;
            }
        }

        #endregion
    } 

Next I created an Attached DependencyProperty that starts the Draging when the MouseDownEvent gets fired. The Draging only gets initialized when the value that gets passed to the Property is "True".
    public static class DragDropBehaviour
    {
        #region DragDropHandler
        ... 
        #endregion

        #region IsDragSource DependencyProperty

        /// 
        /// attached property that defines if the source is a drag source
        /// 
        public static readonly DependencyProperty IsDragSourceProperty =
           DependencyProperty.RegisterAttached("IsDragSource", 
           typeof(bool?), 
           typeof(DragDropBehaviour),
           new PropertyMetadata(null, new IsDragSourceBehaviour().PropertyChangedHandler));

        public static void SetIsDragSource(DependencyObject o, object propertyValue)
        {
            o.SetValue(IsDragSourceProperty, propertyValue);
        }
        public static object GetIsDragSource(DependencyObject o)
        {
            return o.GetValue(IsDragSourceProperty);
        }

        #endregion

        /// <summary>
        /// Internal class that starts the draging
        /// </summary>
        private class IsDragSourceBehaviour : DragDropBehaviourBase
        {
            /// <summary>
            /// Hattach the events
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="oldValue"></param>
            /// <param name="newValue"></param>
            protected override void AdjustEventHandlers(DependencyObject sender, 
                                                        object oldValue, object newValue)
            {
                var element = sender as UIElement;
                if (element == null) 
                    return;

                if (oldValue != null)
                {
                    element.RemoveHandler(UIElement.MouseMoveEvent, 
                                          new MouseEventHandler(OnMouseMove));
                }

                if (newValue != null && newValue is bool && (bool)newValue)
                {
                    element.AddHandler(UIElement.MouseMoveEvent, 
                                       new MouseEventHandler(OnMouseMove));
                }
            }

            /// <summary>
            /// eventhandler for the MouseMoveEvent
            /// </summary>
            private void OnMouseMove(object sender, MouseEventArgs e)
            {
                if (sender is Selector && e.LeftButton == MouseButtonState.Pressed)
                {
                    var lst = (Selector)sender;
                    var selectedItem = lst.SelectedItem;

                    var dragDropEffect = DragDropEffects.Move;

                    if (dragDropEffect != DragDropEffects.None)
                    {
                        DragDropEffects enmEffect = 
                                   DragDrop.DoDragDrop(sender as DependencyObject, 
                                                       selectedItem, dragDropEffect);
                    }
                }
            }
        }
   }


The implementation of the DragDropHandler can be used in different ways.

Firs I tried an approach similar to the way the RelayCommand is implemented with an Object that implements the IDragDropHandler interface and can be used as a Property that gets attached to the DragDropHandlerPeoperty through data binding.
This object accepts a Action and a Func as parameters whereas the Func is optional.
    public class DragDropHandler : IDragDropHandler
    {
        readonly Action<IDataObject, IEnumerable> _drop;
        readonly Func<IDataObject, IEnumerable, bool> _canDrop;

        public DragDropHandler(Action<IDataObject, IEnumerable> drop)
            : this(drop, null)
        {
        }

        public DragDropHandler(Action<IDataObject, IEnumerable> drop, 
                               Func<IDataObject, IEnumerable, bool> canDrop)
        {
            if (drop == null)
                throw new ArgumentNullException("drop");

            _drop = drop;
            _canDrop = canDrop;
        }

        [DebuggerStepThrough]
        public bool CanDrop(IDataObject dropObject, IEnumerable dropTarget)
        {
            if (_canDrop != null)
                return _canDrop(dropObject, dropTarget);

            return true;
        }

        [DebuggerStepThrough]
        public void OnDrop(IDataObject dropObject, IEnumerable dropTarget)
        {
            _drop(dropObject, dropTarget);
        }
    }

In the ViewModel I created a Property of type DragDropHandler. Here I passed a method that accepts a IDataObject and IEnumerable as parameter for the Action<IDataObject, IEnumerable> and a method that accepts a IDataObject and IEnumerable as parameter for the Func<IDataObject, IEnumerable> (alternatively ony if needed) through the constructor. These methods will handle the DropActions similar to the RelayCommand.
The nice thing about this approach is that the DragDopHandler accepts Lambda Expressions as parameters instead of the methods.
        IDragDropHandler _dragDropAction;
        public IDragDropHandler DragDropAction
        {
            get
            {
                if (_dragDropAction == null)
                    _dragDropAction = new DragDropHandler(OnDrop, CanDrop);
                return _dragDropAction;
            }
        }

        public bool CanDrop(IDataObject dropObject, IEnumerable dropTarget)
        {
            if (!(dropTarget is IList))
                return false;
            return !(dropTarget as IList).Contains(dropObject.GetData(typeof(BaseGroup)));
        }

        public void OnDrop(IDataObject dropObject, IEnumerable dropTarget)
        {
            if (dropTarget is IList)
            {
                if (dropObject.GetDataPresent(typeof(BaseGroup)))
                {
                    (dropTarget as IList).Add(dropObject.GetData(typeof(BaseGroup)));
                }
            }
        }

In the XAML I added the AttachedProperties and made a DataBinding to the DragDropAction Property.
            <ListBox IsSynchronizedWithCurrentItem="True"
                     AllowDrop="True"
                     ItemsSource="{Binding Objects}" 
                     i:DragDropBehaviour.DragDropHandler="{Binding DragDropAction}"
                     i:DragDropBehaviour.IsDragSource="True"/>

            <ListBox Grid.Column="1"
                     IsSynchronizedWithCurrentItem="True"
                     AllowDrop="True"
                     ItemsSource="{Binding Objects2}" 
                     i:DragDropBehaviour.DragDropHandler="{Binding DragDropAction}"
                     i:DragDropBehaviour.IsDragSource="True"/>


Alternatively the ViewModel itself could implement the IDragDropHandler interface. This way the Binding can be made directly in the ViewModel instead of creating a roundtrip over the DragDropHandler object.
    internal class DragDropListBoxViewModel : IDragDropHandler
    {
        #region DragDropAction

        public bool CanDrop(IDataObject dropObject, IEnumerable dropTarget)
        {
            if (!(dropTarget is IList))
                return false;
            return !(dropTarget as IList).Contains(dropObject.GetData(typeof(BaseGroup)));
        }

        public void OnDrop(IDataObject dropObject, IEnumerable dropTarget)
        {
            if (dropTarget is IList)
            {
                if (dropObject.GetDataPresent(typeof(BaseGroup)))
                {
                    (dropTarget as IList).Add(dropObject.GetData(typeof(BaseGroup)));
                }
            }
        }

        #endregion
    }

The DataBinding can be made by directly binding to the ViewModel.
            <ListBox IsSynchronizedWithCurrentItem="True"
                     AllowDrop="True"
                     ItemsSource="{Binding Objects}" 
                     i:DragDropBehaviour.DragDropHandler="{Binding}"
                     i:DragDropBehaviour.IsDragSource="True"/>

            <ListBox Grid.Column="3" 
                     IsSynchronizedWithCurrentItem="True"
                     AllowDrop="True"
                     ItemsSource="{Binding Objects2}" 
                     i:DragDropBehaviour.DragDropHandler="{Binding}"
                     i:DragDropBehaviour.IsDragSource="True"/>