使用MVVM模式实时更新列表中的项目

时间:2015-11-13 15:51:21

标签: c# wpf mvvm

在我的ViewModel中有一个ObservableCollection,它在ViewModel加载时填充。

public ObservableCollection<Price> ItemPrices
{
    get
    {
        return _itemPrices;
    }
    set
    {
        _itemPrices = value;
        OnPropertyChanged("ItemPrices");
    }
}

这将绑定到ListView,而ListView又包含用于布局目的的GridView。 GridView中的项目是Image:

<ListView ItemsSource="{Binding ItemPrices}">
    <ListView.View>
        <GridView>

            <GridViewColumn Header="" Width="auto">
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <Button Width="30" HorizontalAlignment="Right" Margin="5" CommandParameter="{Binding}"
                                Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.DocumentCommand}" >
                            <Image HorizontalAlignment="Center" VerticalAlignment="Center" Source="{Binding Converter={StaticResource PriceDocumentImageConverter} }" />
                        </Button>
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>

        </GridView>
    </ListView.View>
</ListView>

源内部的绑定提供了我想在这里做什么的线索:根据绑定对象的一个​​属性的状态更改图像的来源。我需要实时发生这种情况,因此,当用户更改相应的属性时,图像会相应更改。

首次加载此屏幕时,它会按预期工作。我根据对象的状态获得正确的图像源。但是,如果我通过UI更新对象,则图像永远不会更改 - 即使我可以看到对象的状态在数据库中发生了变化。

我正在为ItemPrices引发适当的OnPropertyChanged事件。

起初,我认为使用转换器可能是错误的方法。所以我换了一个触发器来代替:

<Image HorizontalAlignment="Center" VerticalAlignment="Center">
    <Image.Style>
        <Style TargetType="{x:Type Image}">
            <Setter Property="Source" Value="/Resources/Icons/Document-Add.png" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding HasDocument}" Value="True">
                    <Setter Property="Source" Value="/Resources/Icons/Document-View.png" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Image.Style>
</Image>

但这也不起作用。

所以我想我会在保存后尝试刷新ObservableCollection,返回数据库以获取我刚刚保存的一组新对象 - 但这也不起作用。< / p>

我以前做过这样的事情,但在那些情况下,我已经能够使用并更新集合中的单个项目 - 例如一个SelectedItem,例如因为我想要改变什么时候用户点击它。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

当您需要替换整个集合时,使用OnPropertyChanged()在该访问器中是很好的。但是它不会改变属性的变化。

您需要在属性本身上调用OnPropertyChanged()。

<强>更新

此外,Observable Collections只会在添加,删除项目或刷新整个列表时触发更新&#34;

https://msdn.microsoft.com/en-us/library/ms668604(v=vs.110).aspx