Tee
Tee

Reputation: 39

how do you Notify the ViewModel if you change values of a collection in the View

I have ListView in my xaml(View) whose itemsSource is bound to an Observable collection.

MyView:

        <ListView x:Name="TestVariables" 
             ItemsSource="{Binding TestVariables}"
             Grid.Row="1"
             Grid.Column="1"
             Grid.ColumnSpan="3">
        <ListView.ItemTemplate>
            <DataTemplate>
                <Grid Background="White" Width="350">
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto"/>
                    </Grid.RowDefinitions>

                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="175"/>
                        <ColumnDefinition Width="175"/>
                    </Grid.ColumnDefinitions>

                    <TextBlock Grid.Row="0"
                               Grid.Column="0"
                               Text="{Binding Key}"/>

                    <TextBox Grid.Row="0"
                               Grid.Column="1"
                               Text="{Binding Value}"/>

                </Grid>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

Question: So when i run my app and change my TextBox values, how do i get a new collection in my view model which has those changes only? I want to use that new collection somewhere in my code. In other words how do i notify my viewmodel of these changes?

For example if i run this, i would get: age 23, sex female, height 2

if i change my textboxes to : age 24, sex male, height 2

I want to build a new collection in my viewModel of: age 24, sex male

Here is my ViewModel:

public class MainViewModel : ViewModelBase { public ObservableCollection TestVariables { get; set; }

    public MainViewModel()
    {
        TestVariables= new ObservableCollection<TestVariable>
        {
            new TestVariable() {Key = "age", Value = 23},
            new TestVariable() {Key = "sex", Value = "female"},
            new TestVariable() {Key = "height", Value = 2}
        };
    }
}

TestVarible Class :

public class TestVariable
{
    public string Key { get; set; }
    public object Value { get; set;}

}

}

Thanks

Upvotes: 0

Views: 386

Answers (1)

You should notify changes for TestVariables property too. And then set binding mode as TwoWay binding on the UI.

private ObservableCollection<TestVariable> testVariables;
public ObservableCollection<TestVariable> TestVariables 
{ 
   get{return testVariables;}
   set
   {
     if(testVariables != value)
       {
         testVariables = value;
         OnPropertyChanged("TestVariables");
       }
   }
} 

Upvotes: 1

Related Questions