I have created wpf code in the main window ,now I want to use MVVM.
I have copied all the data from the xaml main window to user control and created new class on
the view model folder with the code which is in the xaml.cs class
currently there is two issue
1.In the main window I refer to ListBox as showen below ,and now probably the user control doesnt know
about the model view class,how should I bound them?
here for example I have error on the: ListBox.ItemsSource = _UsersList;
internal 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; }
the xaml is
<UserControl x:Class="Wizard01.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="FullName" 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"/><TextBox x:Name="Company" AcceptsReturn="True" AllowDrop="True" PreviewDragEnter="DropText_PreviewDragEnter" PreviewDrop="DropText_PreviewDrop" PreviewMouseDown="DropText_PreviewMouseDown" Grid.Column="1" HorizontalAlignment="Left" Height="23" Margin="351,117,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="120"/>
2. In the main window I init the objects,how should I do it now?
public MainWindow() { InitializeComponent(); _UsersList.Add(new User {Name = "Mike"}); _UsersList.Add(new User {Name = "Jhon"}); ListBox.ItemsSource = _UsersList; }