Treeview _ improvement for Windows (1)

Source: Internet
Author: User
Tags visual studio 2010

Attention, friends! Starting from this article, we will use Visual Studio 2010 and blend 4 as the main development tools.

This article includes:
  • Converter binding, conversion, and template modification improve the appearance of treeviewitem during Mouseover
  • Behavior additional drag Behavior
  • Adorner Decoration & drag effect
Improved Treeview appearance
  1. Create a new WPF application.
    (Note that vs2010 and blend 4 are used for development in this section. If vs 08 or blend 3 is used, the project cannot be opened normally. Sorry! But it does not affect code learning !)
  2. Create a user control. For more information, see create a basic Treeview with blend in the previous section.
    (The entire win7 learning version is not small. The following chapters will also create user controls that inherit usercontrol or control to facilitate management and reuse)
  3. The actual controltemplate layout of treeviewitem is as follows: a grid with two rows and three columns:
  4. The default layout causes the child node (itemhost) to always offset the width of the first column (value: 19) to the right of the parent node ).
    To achieve the offset effect and enable itemhost to span all columns (so that border can fill the entire row), modify the grid in two rows and one column, the left side of stackpanel is filled with margin (value: 19 ):
  5. The margin binding of stackpanel in XAML is as follows (the bound object is treeviewitem ):
    <StackPanel x:Name="stackPanel"                                            Orientation="Horizontal"                                            Margin="{Binding RelativeSource=
    {RelativeSource FindAncestor, AncestorType=TreeViewItem, AncestorLevel=1}, Converter={StaticResource ConverterLoginMarginLeft}}">
  6. The converterloginmarginleft class is defined as follows (using visualtreehelper ):

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture){    double columnWidth = 19.0;    double left = 0.0;    UIElement element = value as TreeViewItem;    while (element.GetType() != typeof(TreeView))    {        element = (UIElement)VisualTreeHelper.GetParent(element);        if (element.GetType() == typeof(TreeViewItem))            left += columnWidth;    }    return new Thickness(left,0,0,0);}
  7. First, bind the stackpanel to the parent node, obtain its margin, and add a value (such as 19) to the original node ), however, the layout order of the WPF Layout System (if mode = onewaytosource is used) and the target data update of Converter in oneway mode does not cause data source changes, as a result, when the upper-level stackpanel is searched, the margin value does not increase (if model = default), So border fails to fill the entire line.
Additional behavior, decorator
  1. To implement additional behavior, first add reference: system. windows. interactivity. DLL (you also need to reference the corresponding namespace. We recommend that you first tap the code, and then press the shitf + ALT + F10 prompt to add the namespace)
  2. Create a class and inherit the behavior <t> interface.

    Note that the behavior is directly applied to the itemscontrol (Treeview) instead of the treeviewitem.

    As described later, the main display control will have multiple display views. If the drag and drop behavior is not flexible for each view, and if the behavior is appended to the dragged object, when you press Ctrl to select multiple objects, it is difficult to simulate multiple objects dragged by win7 decoration.

    class ItemsControlDragDropBehavior:Behavior<ItemsControl>
  3. First method onattached and ondetaching, and add the corresponding delegate event:
    Protected override void onattached () {base. onattached (); this. associatedobject. previewmouseleftbuttondown + = new mousebuttoneventhandler (associatedobject_previewmouseleftbuttondown );......} protected override void ondetaching () {// likewise ......;}
  4. When you press the mouse: _ isdown = true;

    When moving the mouse, you need to judge: (key logic)

    Note: When _ adornerlayer. capturemouse () is called, The associatedobject_previewmousemove (Object sender, mouseeventargs e) event is executed again.

    void AssociatedObject_PreviewMouseMove(object sender, MouseEventArgs e){    if (_isDown == false)        return;    if (_isDragging == true)    {        DragMoved(e);    }    else if (OverMiniDistance(e))    {        DragStarted(e);    }}
    private void DragStarted(MouseEventArgs e){    _isDragging = true;    _adornerlayer.CaptureMouse();    _startPoint = e.GetPosition(_adornerlayer);    _adornerlayer = this.AssociatedObject as ItemsControl;    Object data = Utilities.GetDataContext(_adornerlayer, _startPoint);    _adorner = new TreeViewItemAdorner(_adornerlayer, data);    AdornerLayer.GetAdornerLayer(_adornerlayer).Add(_adorner);}

  5. The getdatacontext method above (This avoids the need to find a specific control type, and the static method is defined in the utilities. CS tool class ):
    public static object GetDataContext(ItemsControl itemsControl, Point p){    FrameworkElement element = itemsControl.InputHitTest(p) as FrameworkElement;    var data = element.DataContext;    return data;}

  6. Finally, let the mouse go.
  7. Here, the mouse moves only (actually by changing the attributes of the treeviewitemadorner modifier ):
    private void DragMoved(MouseEventArgs e){    Point CurrentPosition = e.GetPosition(_adornerlayer);    _adorner.LeftOffset = CurrentPosition.X - _startPoint.X;    _adorner.TopOffset = CurrentPosition.Y - _startPoint.Y;}
  8. Create a class that inherits the adorner and call the constructor of the base class to know the object on which the decoration is applied:
    class TreeViewItemAdorner : Adornerpublic TreeViewItemAdorner(UIElement adornedElement, object data)    : base(adornedElement)
  9. To obtain a copy of the decorated element, you can use the constructor:

    Visualbrush _ brush = new visualbrush (adornedelement );

    For example, you can fill in _ brush in rectangle.

    Of course, in this example, the type of the uielement adornerelement parameter I passed in is itemscontrol (that is, the entire Treeview control). If you want to obtain the selected treeviewitem, you can use itemcontainergenerator or visualtreehelper for recursive search.

    If you only add Decorations to the elements to be decorated, The onrender method is generally reloaded and the method is:

    Protected override void onrender (drawingcontext ){......};

    For example:

    Drawingcontext. drawimage (Bi, adornedelementrect );

    You can add animations and opacity. You can query the msdn adorner or download the sample code by using specific APIs.

  10. Finally, compile the program (CTRL + Shift + B). You can drag itemscontroldragdropbehavior in the assets panel of blend (in behaviors ).

    Note: This behavior can be modified and reused in the main display control to be introduced later.

    Therefore, the T type in class itemscontroldragdropbehavior: behavior <itemscontrol> is itemscontrol.

    In the code, try to avoid specific types (such as Treeview ).

  11. To avoid unnecessary judgment logic, note that itemscontroldragdropbehavior only processes the drag and drop of items, so you can remove the red rectangle, alternatively, you can directly create a controltemplate for a Treeview with only itemspresenter, or set the scrollviewer control horizontalscrollbarvisibility = "disabled" to make the Treeview control appear in a horizontal scroll bar, this prevents errors when you drag a scroll bar, and it is not appropriate if there are multiple treeviews in the directory tree. Also, sometimes because scollviewer may occupy unlimited space, dragging cannot be removed from the scollviewer range.

    You can also add logic to determine the type of the drag object.

    A simple implementation method is to place the horizontal and vertical scroll bars outside the entire directory tree.

  12. Finally, drag the new user control to mainwindow and add a gridspitter.
  13. Figure:

Summary
  1. By modifying the template style of the basic control, you can customize the appearance. Note that you can use the blend visual interface to learn the layout and template style of the default control.
  2. Visualtreehelper and itemcontainergenerator have several common static method lookup controls.

    For example, you can find the element controls in the style template.
  3. The additional behavior is loosely coupled and can be reused flexibly.

    Unlike additional attributes, you can use additional behaviors to process behaviors. When binding is involved, you can use additional attributes.
  4. You can create a tool class for the methods commonly used in the entire application. The method is a static method. Such as obtaining mouse coordinates.
For more information about Treeview drop, see the following section. If you have any suggestions or comments, please leave a message.

Code download

Technorati labels: WPF, Treeview, adorner, behavior
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.