2011-06-08 63 views
1

與庫存數據綁定應用程序開始,我這個替換MainPage執行如何從Databound windows phone應用程序中刪除項目?

<StackPanel Margin="0,0,0,17" Width="432"> 
<TextBlock Text="{Binding LineOne}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}"/> 
     <TextBlock Text="{Binding LineTwo}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/> 
</StackPanel> 

的XAML:

<StackPanel Margin="0,0,0,17" Width="432"> 
<TextBlock Name="ItemName" Margin="10,10,0,0" Text="{Binding LineOne}" TextWrapping="Wrap" Style="{StaticResource PhoneTextSubtleStyle}" Grid.Column="0" /> 
<Button Grid.Column="1" Click="Button_Click" BorderThickness="0" Height="40" HorizontalAlignment="Center"> 
</StackPanel> 

在Button_Click(),我想從項目中移除該項目。我知道語法會像App.ViewModel.Items.Remove(東西) ,但我錯過了什麼是。如何根據顯示的LineOne的值確保刪除正確的項目?

感謝您的期待。

回答

2

有幾種方法可以做到這一點。最好的方法是使用ICommand。但是你也需要添加一個CommandButton類來保存參考和參數。

如果你想要一個快速的解決方法,那麼button click事件中的sender對象應該是你單擊的按鈕,並且它的DataContext屬性應該是列表項。一個令人討厭的黑客攻擊,但是如果你只是在學習這些工具,那麼比沿着ICommand路徑的工作少得多。

private void Button_Click(object sender, RoutedEventArgs e) { 
    App.ViewModel.Items.Remove((ItemViewModel)((Button)sender).DataContext); 
} 
+0

Windows Phone目前尚未實施ICommand。爲了獲得類似的效果,您需要查看Caliburn或MVVM Light之類的MVVM框架。這些允許您將列表項目作爲「消息」或參數發送到從列表中刪除項目的方法。但是,從初學者階段開始大約需要10步。 :) – 2011-06-08 02:01:04

+0

Chris,我收到錯誤:「參數1:無法從'對象'轉換爲'tmp_FavoritesUpdate.ItemViewModel'」 – Freakishly 2011-06-08 02:08:00

+0

此示例中的列表項目類型爲「ItemViewModel」而不是「ListItem」。我正在玩一些不同的演員選項,以確保我們獲得正確的項目。 – 2011-06-08 02:18:56

相關問題