John Jerrby
John Jerrby

Reputation: 1703

How to bind the viewModel to view

I have created WPF code in the main window ,now I want to use MVVM. I have copied all the data from the xaml of the main window to user control and created new class on the view model folder with the code which is in the xaml.cs class

in the user control class I add

public UserControl()
        {
            InitializeComponent();
     this.DataContext = new ModelView();
        }

currently there is two issue

1.In the main window I refer to ListBox as showen below ,and now probably the user control doesn't know about it,how should I solve it?

the error on the listBox is "cannot access non-static property item source in static context".

here for example I have error on the: ListBox.ItemsSource = _UsersList;

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


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

        public void initUsers()
        {
            _UsersList.Add(new User {Name = "Mike"});
            _UsersList.Add(new User {Name = "Jhon"});


            ListBox.ItemsSource = _UsersList;
        }

2.in addition in the view model I copied some code from the main window like method DropText_PreviewDragEnter which is refereed in Previ,ewDragEnter below in the XAML and now have error ,how should I avoid that?

    <TextBox x:Name="FullName"  
              AcceptsReturn="True"
              AllowDrop="True" 
              PreviewDragEnter="DropText_PreviewDragEnter"


              HorizontalAlignment="Left" Height="20" Margin="360,70,0,0" TextWrapping="Wrap" Text="" 
              VerticalAlignment="Top" Width="70"/>

Upvotes: 0

Views: 145

Answers (2)

Mike Schwartz
Mike Schwartz

Reputation: 2212

First off, you are setting the ItemsSource in the wrong place - you need to set the ItemsSource in the xaml page of your UserControl.

<ListBox ItemsSource="{Binding _UsersList}"

As for the second question - you haven't given us enough to help you with. Do you have a code behind event associated with that event?

Upvotes: 1

MichaelLo
MichaelLo

Reputation: 1319

Regarding #1, your are refering the class ListBox, and not an instance of that class. It is similar to doing somthing like:

string = "a".

What you should do is write a ListBox in your xaml, in which you will bind it's ItemSource property into your UserList property in the view model.

I suggest you find an example on the internet for binding a listbox to see the concept.

Regarding #2, it is not clear what is the error you are reciving, but make sure you have implemented a DropText_PreviewDragEnter method in the code behind of the xaml.

Upvotes: 2

Related Questions