none
Code Example of ObservableCollection<T> NOT in code behind (MVVM)

    Question

  • I am needing to see an example of creating and binding an ObservableCollection in an MVVM model.  No code behind. I want to be able to create an ObservableCollection that will hold data input from a textbox and have it's elements bound to a listbox in the GUI.
    Thursday, July 03, 2014 9:19 PM

Answers

  • Just bind the ListBox's ItemsSource property to a view model property of type ObservableCollection<T>:

    class ViewModel
        {
            public ViewModel()
            {
                this.MyCollection = new ObservableCollection<string>();
                this.MyCollection.Add("A");
                this.MyCollection.Add("B");
                this.MyCollection.Add("C");
            }
            public ObservableCollection<string> MyCollection { get; set; }
        }

    <Window x:Class="WpfApplication36.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:local="clr-namespace:WpfApplication36"
            Title="MainWindow" Height="350" Width="525">
        <Window.DataContext>
            <local:ViewModel/>
        </Window.DataContext>
        <Grid>
            <ListBox ItemsSource="{Binding MyCollection}"></ListBox>
        </Grid>
    </Window>

    You can then add an item to the ObservableCollection at runtime and the ListView will display the newly added item automatically.

    Regarding the TextBox, you will have to more specific. You could bind the TextBox's Text property to a string property of the view model and then access this value from anywhere in the view model.

    Please refer to the following article for more information about how to implement the MVVM pattern in WPF applications: http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

    • Marked as answer by MootchMonster Tuesday, July 08, 2014 1:12 PM
    Thursday, July 03, 2014 9:44 PM