【问题标题】:how do you Notify the ViewModel of values of a collection which changed in the View C#你如何通知 ViewModel 在 View C# 中更改的集合的值
【发布时间】:2014-11-05 14:06:23
【问题描述】:

我的 View 中有 ListView,其 itemsSource 绑定到 Observable 集合。这是我的看法

<ListView x:Name="Details" 
         ItemsSource="{Binding Details}"
         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 值时,如何在我的 viewModel 中获得一个仅具有这些更改的新集合?我想要一个我只更改过的值的集合。目前,我得到了一组我已更改的值和旧值。这是我的 MainViewModel:

private ObservableCollection<Details> _details;
public ObservableCollection<Details> Details
    {
        get { return _details; }
        set
        {
            _details= value;
            RaisePropertyChanged();
        }
    }

 public MainViewModel()
{
    Details= new ObservableCollection<Details>
    {
        new Details() {Key = "age", Value = 25},
        new Details() {Key = "sex", Value = "female"},
        new Details() {Key = "height", Value = 3}
    };
}

细节类:

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

在上面的代码中,如果我将年龄更改为 20,,我将得到一个集合:(年龄 20,性别女性,身高 3) 但我只想要(20 岁),即我只更改了 textBox 的 Details 对象!!。我不想比较原始收藏和新收藏来获得它。有什么办法可以触发一个事件或那些很长的东西。

谢谢

【问题讨论】:

  • 完全是VM逻辑。您应该订阅每个集合值的 PropertyChanged 事件,并在处理程序中将作为事件源的项目放入单独的集合中。

标签: c# mvvm


【解决方案1】:

您需要为 ObservableCollection CollectionChanged 事件连接一个事件处理程序。然后,处理程序将把它传递给它一个 EventArguments: http://msdn.microsoft.com/en-us/library/system.collections.specialized.notifycollectionchangedeventargs(v=vs.110).aspx

请注意,您将能够根据您的请求查看新项目。

这篇文章展示了一个非常清晰的例子来说明如何做到这一点......

Notify ObservableCollection when Item changes

现在,如果您想更深入地研究,并且只获取已更改的属性值之一,则需要在 Details 类中实现您自己的通知系统。有很多方法可以做到这一点,一种是臭名昭著的 DepedencyProperty 本身,它有许多用于更改的钩子。但是您可以简单地将 EventHanlder 或通用 EventHandler 实现为类定义中的静态变量。这允许其他类“连接”到事件。

【讨论】:

    猜你喜欢
    • 2014-12-21
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 2018-07-22
    • 2021-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多