mileyH
mileyH

Reputation: 176

Change main window implementation to user control

I need to replace the following code usercontrol instead of main window (of course the main window is just calling to the userControl),while doing that I have the following problem.

Currently I tried to add the following code like in the main window in the

constructor of the usercontrol after the

public partial class UserControl: UserControl
    {
        private static MappingViewModelView _modelViewInstance;

        public UserControl()
        {
            InitializeComponent();
            _modelViewInstance = new MappingViewModelView();
            DataContext = _modelViewInstance;

            var source = Resources["source"] as CollectionViewSource;
            if (source != null)
                source.Source = _modelViewInstance.UserList;

            ListBox.SelectionChanged += listbox_SelectionChanged;

But now in the user control there is no event SelectionChanged for list box (using the intlisense) just ListBox.SelectionChangedEvent which is not fit the original solution from the main window which is

ListBox.SelectionChanged += listbox_SelectionChanged;

error which is given if i put the exact code is: Cannot access non-static event 'SelectionChanged' in static context

Any idea why the list box behave different in the user control?

public partial class MainWindow : Window
{
   public ObservableCollection<User> _UsersList = new ObservableCollection<User>();
   private readonly Dictionary<string, string> _mapping = new Dictionary<string, string>();
   private const string DRAG_SOURCE = "DragSource";

   public MainWindow()
   {

      InitializeComponent();
      _UsersList.Add(new User { Name = "Jhon" });
      _UsersList.Add(new User { Name = "Mike" });
      _UsersList.Add(new User { Name = "Alex" });
      _UsersList.Add(new User { Name = "Darl" });

      CollectionViewSource source = this.Resources["source"] as CollectionViewSource;
      source.Source = _UsersList;
      ListBox.SelectionChanged += listbox_SelectionChanged;

      DataObject.AddCopyingHandler(text1, DragCopy);
      DataObject.AddCopyingHandler(text2, DragCopy);
   }

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


   private void listbox_SelectionChanged(object sender, SelectionChangedEventArgs e)
   {
     if (e.AddedItems.Count == 1)
     {
         if (ListBox.SelectedItems.Count > 0)
         {
            var mySelectedItem = ListBox.SelectedItem as User;
            if (mySelectedItem != null)
            {
                DragDrop.DoDragDrop(ListBox, mySelectedItem,
                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))
      {
         DataObject data = e.Data as DataObject;
         User user = data.GetData(typeof(User)) as User;
         textbox.Tag = user;

         var name = user.Name;
         textbox.Text += name;
         textbox.Focus();
         textbox.CaretIndex = textbox.Text.Length;
         e.Handled = true;
         var remove = _UsersList.Remove((User)ListBox.SelectedItem);

         if (!_mapping.ContainsKey(textbox.Name))
             _mapping.Add(textbox.Name, name);
      }

      e.Handled = true;
   }

   private void DropText_PreviewDragOver(object sender, DragEventArgs e)
   {
      e.Handled = true;
   }

   private void ListBox_Drop(object sender, DragEventArgs e)
   {
       DataObject data = e.Data as DataObject;
       if (data != null)
       {
           User user = data.GetData(typeof(User)) as User;
           if (user != null && !_UsersList.Contains(user))
               _UsersList.Add(user);
       }


       TextBox txtBox = e.Data.GetData(DRAG_SOURCE) as TextBox;
       if (txtBox != null)
       {
           if (_mapping.ContainsKey(txtBox.Name))
               _mapping.Remove(txtBox.Name);
           txtBox.Dispatcher.BeginInvoke((Action)(() => { txtBox.Text = string.Empty; }), System.Windows.Threading.DispatcherPriority.Normal);
       }
       e.Handled = true; 
   }

   private void DragCopy(object sender, DataObjectCopyingEventArgs e)
   {
      if (e.IsDragDrop)
      {
         e.CancelCommand();
         TextBox txtBox = sender as TextBox;
         if (txtBox != null && txtBox.Tag != null)
         {
             DataObject dataObject = new DataObject(txtBox.Tag);
             dataObject.SetData(DRAG_SOURCE, txtBox);
             DragDrop.DoDragDrop(sender as DependencyObject, dataObject, DragDropEffects.Move | DragDropEffects.Copy);
         }
         e.Handled = true;
      }
   }

   private void DropText_TextChanged(object sender, TextChangedEventArgs e)
   {
      TextBox txtBox = sender as TextBox;
      if (txtBox.Text == string.Empty)
      {
         User user = txtBox.Tag as User;

         if(user != null && !_UsersList.Contains(user))
            _UsersList.Add(user);

         if (_mapping.ContainsKey(txtBox.Name))
             _mapping.Remove(txtBox.Name);
      }
   }
}


ListBox x:Name="ListBox" HorizontalAlignment="Left" Height="115"
                      VerticalAlignment="Top" Width="150" ItemsSource="{Binding Source={StaticResource source}}" 
                     DisplayMemberPath="Name"
                     AllowDrop="True" Drop="ListBox_Drop" />

<Window.Resources>
        <CollectionViewSource x:Key="source">
        </CollectionViewSource>
    </Window.Resources>



        <TextBox x:Name="text1"  
                  AcceptsReturn="True"
                  AllowDrop="True" 
                  PreviewDragEnter="DropText_PreviewDragEnter"
                  PreviewDrop="DropText_PreviewDrop"
                  PreviewDragOver="DropText_PreviewDragOver"
                  TextChanged="DropText_TextChanged"
                  Grid.Column="1"
                  HorizontalAlignment="Left" Height="23" TextWrapping="Wrap" 
                  VerticalAlignment="Top" Width="120"/>

        <TextBox x:Name="text2"  
                  AcceptsReturn="True"
                  AllowDrop="True" 
                  PreviewDragEnter="DropText_PreviewDragEnter"
                  PreviewDrop="DropText_PreviewDrop"
                  PreviewDragOver="DropText_PreviewDragOver"
                  TextChanged="DropText_TextChanged"
                  Grid.Column="1"
                  HorizontalAlignment="Left" Height="23" TextWrapping="Wrap"
                  VerticalAlignment="Top" Width="120"/>

Upvotes: 2

Views: 296

Answers (1)

Markus
Markus

Reputation: 22501

If you moved the ListBox to the UserControl, the most likely reasen is that - maybe by accident - the name was changed in the process.
The error message points in this direction as it recognizes ListBox as the type and not as the name of a concrete instance of a ListBox on the UserControl.

Upvotes: 1

Related Questions