2014-10-20 31 views
0

我正嘗試使用MVVM Light向視圖模型發送FlipView控件的當前項目。在Windows應用商店應用中作爲RelayCommandParameter發送FlipViewItem

表示FlipView控制的XAML代碼如下:

<FlipView x:Name="mainFlipView" Margin="0,10,0,10" ItemsSource="{Binding AlbumItems, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"> 
    <FlipView.ItemTemplate> 
     <DataTemplate> 
      <Grid Margin="5"> 
       <Grid.RowDefinitions> 
        <RowDefinition Height="Auto" /> 
         <RowDefinition Height="*" /> 
         <RowDefinition Height="Auto" /> 
       </Grid.RowDefinitions> 

       <TextBlock Text="{Binding Caption}" 
         FontSize="23" 
         HorizontalAlignment="Center" 
         TextAlignment="Center" 
         TextWrapping="Wrap" 
         Margin="10"/> 

       <ScrollViewer Grid.Row="1" ZoomMode="Enabled"> 
        <uc:ImageViewer FilePath="{Binding ImagePath}" /> 
       </ScrollViewer> 

       <TextBlock Text="{Binding NrOfVotes}" FontSize="20" 
         Grid.Row="2" HorizontalAlignment="Center"       
         Margin="10" /> 
      </Grid> 
     </DataTemplate> 
    </FlipView.ItemTemplate> 
</FlipView> 
... 

含有中繼命令的項目的XAML代碼是:

<Page.BottomAppBar> 
    <CommandBar> 
     <AppBarButton x:Name="appBarButtonDelete" Label="Delete" Icon="Delete" 
         Command="{Binding DeleteItemCommand}" 
         CommandParameter="{Binding ElementName=mainFlipView, Path=SelectedItem}"/> 
    </CommandBar> 
</Page.BottomAppBar> 

在視圖模型中,RelayCommand被聲明和使用方法如下:

public class ResultsPageViewModel : ViewModelBase 
{ 
    public RelayCommand<MyModel> DeleteItemCommand { get; private set; } 

    public ResultsPageViewModel() 
    { 
     this.DeleteItemCommand = new RelayCommand<MyModel>(post => DeleteItem(post)); 
    } 

    public void DeleteItem(MyModel p) 
    { 
     //P is always null here... 
    } 
} 

問題是在DeleteItem函數我總是得到參數爲null。我試過宣佈RelayCommand爲RelayCommand<object>,但問題依然存在。

我也嘗試了「解決方法」方法來聲明MyModel可綁定屬性並將其綁定到FlipView。它有效,但我想知道我在這種情況下做錯了什麼。

預先感謝您!

+1

什麼是AlbumItems的類型? – bit 2014-10-20 08:28:40

+0

這是一個'ObservableCollection ' – rhcpfan 2014-10-20 10:15:28

+0

有什麼想法?謝謝! – rhcpfan 2014-10-27 07:30:09

回答

0

嘗試不同的策略:在正確綁定後直接從ViewModel獲取參數。

XAML

<FlipView x:Name="mainFlipView" 
      Margin="0,10,0,10" 
      ItemsSource="{Binding AlbumItems, Mode=TwoWay }" 
      SelectedItem="{Binding AlbumSelectedItem, Mode=TwoWay}"> 

視圖模型

private MyModel albumSelectedItem; 
public MyModel AlbumSelectedItem 
{ 
    get 
    { 
     return albumSelectedItem; 
    } 

    set 
    { 
     if (value != null && albumSelectedItem != value) 
     { 
      albumSelectedItem = value; 
      RaisePropertyChanged(() => AlbumSelectedItem); 
     } 
    } 
} 

public void DeleteItem(MyModel p) 
{ 
    //P is always null here... 
    var pp = AlbumSelectedItem; 
} 

顯然,CommandParameter是沒用的。 ;-)