Quantcast
Channel: Windows Presentation Foundation (WPF) forum
Viewing all articles
Browse latest Browse all 18858

Using MVVM instead of main window for the following code

$
0
0

I'm using the following code which is copy pasted from the main window whichwas working as expected ,

  • I have created View which is user control and put the code of the code from the main window XAML
  • In the View model I put reference for the User model
  • In the user control I put the code for from the the main window which is related to the event handlers  for example the DropText_PreviewDragEnter & listbox_SelectionChanged

Currently I have 2 issues in the User Control which Im not sure how to overcome...

1. errors in the user control for all the occurrence of the ListBox (for example from listbox_SelectionChanged  ystem.Windows.Controls.ListBox.SelectedItems.Count > 0 . the Selected items are marked at red with the following error

"cannot access non-static property SelectedItems item source in static context". ,not sure what is the reason since in the main window it was the same as static.

2.Since I have copied the code from the main window there is references to user object in the user controlwhich I believe is not acceptable in MVVM ,how should I change it ? for example

var mySelectedItem = System.Windows.Controls.ListBox.SelectedItem as User;

or 

 bool remove = _UsersList.Remove((User) System.Windows.Controls.ListBox.SelectedItem);

Here is the code.

I will appreciate your help !

The view model 

public partial class ModelView : UserControl
    {
        private const string DRAG_SOURCE = "DragSource";

        public ModelView()
        {
            InitializeComponent();
            DataContext = new ModelView();
        }


        private void listbox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count == 1)
            {
                if (System.Windows.Controls.ListBox.SelectedItems.Count > 0)
                {
                    var mySelectedItem = System.Windows.Controls.ListBox.SelectedItem as User;
                    if (mySelectedItem != null)
                    {
                        DragDrop.DoDragDrop(System.Windows.Controls.ListBox, mySelectedItem.ToString(),
                            DragDropEffects.Copy | DragDropEffects.Move);
                    }
                }
            }
        }

        private void DropText_PreviewDragEnter(object sender, DragEventArgs e)
        {
            e.Effects = DragDropEffects.None;
        }


        private void DropText_PreviewDrop(object sender, DragEventArgs e)
        {
            var textbox = (TextBox) sender;

            if (!(textbox.Text.Length > 0))
            {
                string name = e.Data.GetData(DataFormats.StringFormat).ToString();
                textbox.Text += name;
                textbox.Focus();
                textbox.CaretIndex = textbox.Text.Length;
                e.Handled = true;
                bool remove = _UsersList.Remove((User) System.Windows.Controls.ListBox.SelectedItem);
            }
            else
            {
                e.Handled = true;
            }
        }


        //Drag Over from text box to List box


        private void ListBox_PreviewDrop(object sender, DragEventArgs e)
        {
            object dragSource = e.Data.GetData(DRAG_SOURCE);
            if (dragSource != null && dragSource is TextBox)
            {
                (dragSource as TextBox).Text = String.Empty;
            }
            if (!String.IsNullOrEmpty(e.Data.GetData(DataFormats.StringFormat).ToString()) && dragSource is TextBox)
            {
                _UsersList.Add(new User {Name = e.Data.GetData(DataFormats.StringFormat).ToString()});
            }
            else
            {
                e.Handled = true;
            }
        }

        private void DropText_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            var textBox = (TextBox) sender;
            if (textBox != null)
            {
                var dataObject = new DataObject((textBox).Text);
                dataObject.SetData("DragSource", sender);
                DragDrop.DoDragDrop(textBox, dataObject, DragDropEffects.Copy | DragDropEffects.Move);
            }
        }
    }

The Xaml is

<UserControl x:Class="Wiz.Views.ModelView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" d:DesignHeight="680" d:DesignWidth="1000"><Grid><ListBox x:Name="ListBox" HorizontalAlignment="Left" Height="165" Margin="100,75,0,0" VerticalAlignment="Top" Width="80" ItemsSource="{Binding userList}" SelectionChanged="listbox_SelectionChanged" PreviewDrop="ListBox_PreviewDrop" AllowDrop="True" /><TextBox x:Name="name1" AcceptsReturn="True" AllowDrop="True" PreviewDragEnter="DropText_PreviewDragEnter" PreviewDrop="DropText_PreviewDrop" PreviewMouseDown="DropText_PreviewMouseDown" HorizontalAlignment="Left" Height="20" Margin="360,70,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="70"/>

....


The model view

    internal class ModelView
    {
        private ObservableCollection<User> _UsersList = new ObservableCollection<User>();

        public ObservableCollection<User> UserList
        {
            get { return _UsersList; }
        }

        public void InitUsers()
        {
            _UsersList.Add(new User {Name = "Jhon"});
            _UsersList.Add(new User {Name = "Mike"});
            _UsersList.Add(new User {Name = "Magnus"});
            //Sort the User collection
            ICollectionView usersView = CollectionViewSource.GetDefaultView(_UsersList);
            usersView.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending));
        }
    }



Viewing all articles
Browse latest Browse all 18858

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>