【问题标题】:how do you Notify the ViewModel if you change values of a collection in the View如果您更改视图中集合的值,您如何通知 ViewModel
【发布时间】:2014-12-21 17:11:13
【问题描述】:

我的 xaml(View) 中有 ListView,其 itemsSource 绑定到 Observable 集合。

我的视图:

        <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>

问题:那么当我运行我的应用程序并更改我的 TextBox 值时,我如何在我的视图模型中获得一个仅具有这些更改的新集合?我想在我的代码中的某个地方使用那个新集合。换句话说,我如何通知我的视图模型这些更改?

例如,如果我运行这个,我会得到:23 岁, 性女性, 高度2

如果我将文本框更改为:24 岁, 性别男, 高度2

我想在我的 viewModel 中构建一个新集合:年龄 24, 性男性

这是我的 ViewModel:

公共类 MainViewModel : ViewModelBase { 公共 ObservableCollection TestVariables { get;放; }

    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 类:

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

}

}

谢谢

【问题讨论】:

  • 尝试将Binding模式设置为TwoWay。类似ItemsSource="{Binding Path=TestVariables, Mode=TwoWay}".
  • 将您自己的事件处理程序附加到每个集合对象上的 PropertyChanged。使用 Viewmodel 上的集合更改事件来附加您的处理程序。当然 testvariable 必须实现 INotifyPropertyChanged。

标签: c# mvvm


【解决方案1】:

您也应该通知 TestVariables 属性的更改。然后在 UI 上设置绑定模式为双向绑定。

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

【讨论】:

  • @Tee,如果有帮助,请阅读What should I do when someone answers my question?accept 他的回答。谢谢。
  • 上述解决方案有效,但后来我注意到我还想要一个仅更改的值的集合。 Raising Property changed for the entire collection 给了我一个包含我没有改变的值的集合。我只想要一个已经改变的值的集合。使用上面的示例,如果我将年龄更改为 26,我应该只得到它,而不是:26 岁,性别女性,身高 2
猜你喜欢
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
  • 2019-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-28
相关资源
最近更新 更多