Drag in MVVM mode and in MVVM Mode

Source: Internet
Author: User

Drag in MVVM mode and in MVVM Mode

Take a look at the article before it starts.

We can drag a game to ListBox, and ListBox can also accept the drag data, but we cannot drag a game type to it.

Therefore, when the drag and drop operation starts, we must add some restrictions to avoid receiving incorrect data.

 

 

Item entity

CS

    public class ItemModel : ViewModelBase    {        public string ItemName { get; set; }    }

 

Group entity

CS

Public class GroupModel: ViewModelBase {// <summary> // group name // </summary> public string GroupName {get; set;} private int groupCount; /// <summary> // number of groups /// </summary> public int GroupCount {get {return groupCount;} set {groupCount = value; base. raisePropertyChanged ("GroupCount") ;}/// <summary> // subclass set /// </summary> public ObservableCollection <ItemModel> ItemModelList {get; set ;}}

 

Create a template for the "game" entity

XAML

<HierarchicalDataTemplate x:Key="template_Item">       <TextBlock Text="{Binding ItemName}"/></HierarchicalDataTemplate>

 

Create a template for the "game group" entity

XAML

<HierarchicalDataTemplate x:Key="template_Group" ItemsSource="{Binding ItemModelList}" ItemTemplate="{StaticResource template_Item}">       <StackPanel Orientation="Horizontal">              <TextBlock Text="{Binding GroupName}"/>              <TextBlock Text="{Binding GroupCount}" Margin="5,0,0,0"/>        </StackPanel></HierarchicalDataTemplate>

 

However, when I want to assign values to the TreeView, I think the SelectedItem attribute of the TreeView is not a dependency attribute and does not support the Binding operation.

Therefore, only one control can inherit the TreeView. Extended a MySelectedItem attribute for it. And override the SelectedItemChange event.

Grant the SelectedItem of the TreeView to the extended dependency attribute MySelectedItem. In this way, you can bind the selected item on the interface.

However, because the data objects of each node in the TreeView may have different types, the extended attributes can only be defined as object types.

 

Create a custom tree

CS

Public class MyTreeView: TreeView {public MyTreeView () {}/// <summary> // select a custom TreeView, data Binding // </summary> public object MySelectItem {get {return GetValue (MySelectItemProperty);} set {SetValue (MySelectItemProperty, value );}} public static DependencyProperty MySelectItemProperty = DependencyProperty. register ("MySelectItem", typeof (object), typeof (MyTreeView); // <summary> /// When a change occurs, assign a value to the custom SelectItem attribute /// </summary> /// <param name = "e"> </param> protected override void OnSelectedItemChanged (RoutedPropertyChangedEventArgs <object> e) {if (this. selectedItem! = Null) this. MySelectItem = this. SelectedItem; base. OnSelectedItemChanged (e );}}

XAML

 <mc:MyTreeView x:Name="myTree" MouseMove="TreeView_MouseMove" TextBlock.FontSize="14" MySelectItem="{Binding SelectGame,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" ItemsSource="{Binding GroupSourceList}" ItemTemplate="{StaticResource template_Group}"></mc:MyTreeView>

 

CS

        private TreeViewItem ti = new TreeViewItem();        private void TreeView_MouseMove(object sender, MouseEventArgs e)        {            if (e.LeftButton == MouseButtonState.Pressed)            {                if (myTree.SelectedItem == null)                    return;                DragDrop.DoDragDrop(ti, sender, DragDropEffects.Move);            }        }

The DragDrop. DoDragDrop method needs to input a DependencyObject object to set its drag effect.

However, because TreeView is bound to data, its SelectItem is a data entity. Instead of a DependencyObject object.

So I used a relatively SB method to create a new TreeViewItem. Then set the drag and drop effect.

 

Create ListBox

           <ListBox ItemsSource="{Binding GameSourceList}" AllowDrop="true">                <ListBox.ItemTemplate>                    <DataTemplate>                        <TextBlock Text="{Binding ItemName}"/>                    </DataTemplate>                </ListBox.ItemTemplate>                <i:Interaction.Triggers>                    <i:EventTrigger EventName="DragEnter">                        <Command:EventToCommand Command="{Binding DragEnterCommand}" PassEventArgsToCommand="True"/>                    </i:EventTrigger>                    <i:EventTrigger EventName="DragOver">                        <Command:EventToCommand Command="{Binding DragEnterCommand}" PassEventArgsToCommand="True"/>                    </i:EventTrigger>                    <i:EventTrigger EventName="Drop">                        <Command:EventToCommand Command="{Binding DropCommand}" PassEventArgsToCommand="True"/>                    </i:EventTrigger>                </i:Interaction.Triggers>            </ListBox>

ViewModel

Public class MainViewModel: ViewModelBase {public MainViewModel () {Init ();} # region Properties // <summary> // data source // </summary> public ObservableCollection <GroupModel> GroupSourceList {get; set ;} /// <summary >/// data source /// </summary> public ObservableCollection <ItemModel> GameSourceList {get; set;} private object selectGame; /// <summary> /// currently selected items /// </summary> public object SelectGame {get {return selectGame;} set {selectGame = value; base. raisePropertyChanged ("SelectGame") ;}# endregion # region Methods private void Init () {GameSourceList = new ObservableCollection <ItemModel> (); GroupSourceList = new ObservableCollection <GroupModel> (); groupModel gp1 = new GroupModel (); # region simulation data gp1.GroupName = "competitive games"; gp1.ItemModelList = new ObservableCollection <ItemModel> (); gp1.ItemModelList. add (new ItemModel () {ItemName = "cs go"}); gp1.ItemModelList. add (new ItemModel () {ItemName = "Starcraft 2"}); gp1.ItemModelList. add (new ItemModel () {ItemName = "FIFA 14"}); gp1.GroupCount = gp1.ItemModelList. count; GroupModel gp2 = new GroupModel (); gp2.GroupName = "online games"; gp2.ItemModelList = new ObservableCollection <ItemModel> (); gp2.ItemModelList. add (new ItemModel () {ItemName = "CS OnLine"}); gp2.ItemModelList. add (new ItemModel () {ItemName = "Street basketball"}); gp2.ItemModelList. add (new ItemModel () {ItemName = "perfect world"}); gp2.GroupCount = gp2.ItemModelList. count; GroupModel gp3 = new GroupModel (); gp3.GroupName = "Casual Games"; gp3.ItemModelList = new ObservableCollection <ItemModel> (); gp3.ItemModelList. add (new ItemModel () {ItemName = "Texas hold'em"}); gp3.ItemModelList. add (new ItemModel () {ItemName = "Street basketball"}); gp3.ItemModelList. add (new ItemModel () {ItemName = "perfect world"}); GroupSourceList. add (gp1); GroupSourceList. add (gp2); GroupSourceList. add (gp3); gp3.GroupCount = gp3.ItemModelList. count; # endregion DragEnterCommand = new RelayCommand <DragEventArgs> (DragEnter); DropCommand = new RelayCommand <DragEventArgs> (Drop);} private void DragEnter (DragEventArgs args) {if (SelectGame. getType () = typeof (ItemModel) // If the dragged object is "game", accept it {args. effects = DragDropEffects. move; System. console. writeLine ("accept");} else {args. effects = DragDropEffects. none; // otherwise, the System will be dragged. console. writeLine ("no accept");} args. handled = true;} private void Drop (DragEventArgs args) {GameSourceList. add (SelectGame as ItemModel); // write the received "game" to ListBox} # endregion # region Commands public ICommand DragEnterCommand {get; set;} public ICommand DropCommand {get; set ;}# endregion}

Here, a simple drag is complete.

QQ 3045568793. Welcome to the discussion. My name is chicken or chicken.

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.