當前我在將列表中的集合保留在mvvm時遇到麻煩,每當我離開並返回到頁面時,列表都會變空。我將如何處理這個問題?有人可以幫我弄這個嗎? 該型號: 我還沒有實現別人還因爲我不能將項目添加到列表保存MVVM中的列表
class CartData
{
public int Cakeprice { get; set; }
public ImageSource ImagePath { get; set; }
public string Caketype { get; set; }
public string Cakename { get; set; }
public int TotalItems { get; set; }
}
視圖模型:
class CartingDataSource : BindableBase
{
public ObservableCollection<CartData> _cartData;
public ObservableCollection<CartData> CartData
{
get {
return _cartData;
}
set {
SetProperty(ref _cartData, value);
}
}
private DelegateCommand _addItemCommand;
public ICommand AddItemCommand
{
get
{
if (_addItemCommand == null)
{
_addItemCommand = new DelegateCommand(AddToCart);
}
return _addItemCommand;
}
}
public void AddToCart() {
CartData.Add(new CartData { Cakename = "Black Forest", Cakeprice = 104 });
}
} 的觀點:
.....
<Page.DataContext>
<vm:CartingDataSource/>
</Page.DataContext>
....
<ListView
x:Name="itemListView"
AutomationProperties.AutomationId="ItemsListView"
AutomationProperties.Name="Items"
TabIndex="1"
Margin="-10,130,0,264"
Padding="120,0,0,60"
ItemsSource="{Binding cartData}"
IsSwipeEnabled="False" Grid.RowSpan="2" ItemClick="itemListView_ItemClick" SelectionChanged="itemListView_SelectionChanged_1" IsItemClickEnabled="True">
<ListView.ItemTemplate>
<DataTemplate>
<Grid Margin="6">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Border Background="{ThemeResource ListViewItemPlaceholderBackgroundThemeBrush}" Width="60" Height="60">
<Image Stretch="UniformToFill" AutomationProperties.Name="{Binding Title}" Source="Assets/TempPic.jpg"/>
</Border>
<StackPanel Grid.Column="1" Margin="10,0,0,0">
<TextBlock Text="{Binding Cakename}" Style="{StaticResource TitleTextBlockStyle}" TextWrapping="NoWrap" MaxHeight="40"/>
<TextBlock Text="{Binding Cakeprice}" Style="{StaticResource CaptionTextBlockStyle}" TextWrapping="NoWrap"/>
</StackPanel>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
<ListView.ItemContainerStyle>
<Style TargetType="FrameworkElement">
<Setter Property="Margin" Value="0,0,0,10"/>
</Style>
</ListView.ItemContainerStyle>
</ListView>
你重新實例代碼的某個地方集合? – cvraman
@cvraman沒有我不能重新實現我的代碼。這裏是我的上一個問題中的完整代碼:http://stackoverflow.com/questions/22163110/maintaining-the-collection-in-a-list-observablecollection –
你在你的棱鏡解決方案上使用哪個容器?是MEF還是Unity?如果Unity是這種情況,那麼您應該注意到容器不會維護對視圖的引用,並且每次導航時都會解析新的實例。因此,當您離開視圖時,該實例將被丟棄,每次您將導航回指定的視圖時,都會獲得一個帶有空集合的新View/ViewModel實例。有關更多信息,請參閱管理相關性的MSDN Prism [章節](http://msdn.microsoft.com/zh-cn/library/ff921140(v = pandp.40).aspx)。 – GOstrowsky