2014-03-03 23 views
0

我在我的WP8應用程序中有一個數據透視視圖,並且我試圖從Click事件「removePin」訪問視圖類中的數據集合。 數據收集的來源是另一個類Pins如何訪問DataCollection

我該如何做到這一點?

這是特定部分

<phone:PivotItem Header="Pins"> 
    <!-- Content Panel --> 
    <Grid x:Name="ContentPanel2" HorizontalAlignment="Left" Height="583" Margin="10,10,0,0" Grid.Row="1" VerticalAlignment="Top" Width="460"> 
     <Grid.ColumnDefinitions> 
      <ColumnDefinition Width="400*"/> 
      <ColumnDefinition Width="0*"/> 
      <ColumnDefinition Width="87*"/> 
     </Grid.ColumnDefinitions> 
     <ListBox x:Name="lstData2" ItemsSource="{Binding DataCollection2, Source={StaticResource PinsCollection}}" 
     Grid.ColumnSpan="3" Foreground="#FF1D53D0" Height="583" VerticalAlignment="Bottom"> 
      <ListBox.ItemTemplate> 
      <DataTemplate> 
       <StackPanel Orientation="Horizontal" Tap="StackPanel_Tap"> 
        <Image Margin="8" VerticalAlignment="Top" Source="{Binding ImageUri}" 
        Width="100" Height="100" /> 
        <StackPanel Height="93" Width="259" > 
         <TextBlock Margin="8" Width="250" TextWrapping="Wrap" VerticalAlignment="Top" HorizontalAlignment="Left" Foreground="#FF1D53D0" 
         Text="{Binding Pinnedname}" Height="33" RenderTransformOrigin="0.5,0.5" FontFamily="Segoe WP SemiLight" FontSize="24" FontWeight="Bold" /> 
         <TextBlock Width="155" Margin="8,0,8,8" VerticalAlignment="Top" 
         HorizontalAlignment="Left" Text="{Binding Status}" Foreground="#FF1D53D0" FontFamily="Segoe WP SemiLight" /> 
       </StackPanel> 
       <toolkit:ContextMenuService.ContextMenu> 
       <toolkit:ContextMenu> 
        <toolkit:MenuItem Header="Remove Pin" Click="RemovePin_Click" Tag="{Binding pinId}"/> 
       </toolkit:ContextMenu> 
       </toolkit:ContextMenuService.ContextMenu> 
      </StackPanel> 
     </DataTemplate> 
     </ListBox.ItemTemplate> 
    </ListBox> 
    <!-- End of Content Panel --> 
    </Grid> 

回答

0

創建自定義命令類的XAML我的代碼片段:

public class CustomCommand : ICommand 
{ 
    Action _exec; 
    public CustomCommand(Action exec) 
    { 
     _exec = exec; 
    } 
    public void Execute(object parameter) 
    { 
     if (_exec != null) _exec(); 
    } 
    public bool CanExecute(object parameter) 
    { 
     return true; 
    } 
    public event EventHandler CanExecuteChanged; 
} 

將它添加到視圖模型銷的元素收集(我認爲它是PinItem)

public CustomCommand RemovePinCommand 
{ 
    get { return (CustomCommand)GetValue(RemovePinCommandProperty); } 
    set { SetValue(RemovePinCommandProperty, value); } 
} 
public static readonly DependencyProperty RemovePinCommandProperty = 
    DependencyProperty.Register("RemovePinCommand", 
    typeof(CustomCommand), 
    typeof(PinItem), 
    new UIPropertyMetadata(null)); 

在這一類的構造函數實現你的這個命令的邏輯:

 RemovePinCommand = new CustomCommand(() => 
     { 
      //delete this pin from its parent collection 
     }); 

最後一步是將命令綁定到菜單項:

<toolkit:MenuItem Header="Remove Pin" Command="{Binding RemovePinCommand}"/>