在我的ViewModel有一個ObservableCollection,這是視圖模型加載時填充。更新項目使用實時MVVM模式
public ObservableCollection<Price> ItemPrices
{
get
{
return _itemPrices;
}
set
{
_itemPrices = value;
OnPropertyChanged("ItemPrices");
}
}
這綁定到一個ListView,而該ListView又包含一個用於佈局目的的GridView。在GridView控件裏面的物品是一個圖片:
<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保存後,要回數據庫來獲取一組新的我剛纔保存的對象 - 但是,這並不工作。
我之前做過類似的事情,但在那些情況下,我已經能夠使用並更新集合中的單個項目 - 比如說SelectedItem,因爲我想在用戶點擊時更改某些內容在上面。
我在做什麼錯?
'ObservableCollection'已經有了'OnPropertyChanged '裏面的事件觸發器,你可以刪除它。 – Karolis
你有沒有文檔調用OnPropertyChanged? – adminSoftDK
@adminSoftDK不 - 但我不明白我可以如何舉一個。我想這是問題的一部分。它是一個計算屬性,取決於Price對象是否具有附加的Document對象。但是,如果ViewModel上沒有單個Price對象來引發事件,那麼我應該在哪裏發送通知? –