2012-07-06 101 views
0

除非將DataContext字段移動到Button的DataTemplate(contlisttemplate)中,否則我的ICommand不會觸發。我在樣式資源中設置了圖像,只要將DataContext字段移動到DataTemplate中,圖像就會消失。圖像和ICommand都應該使用相同的DataContext,所以我不確定它爲什麼不起作用。ICommand不會觸發

這是我的代碼片段下面。

DataContext="{Binding LongListViewModel, Source={StaticResource viewModelLocator}}" 

<i:Interaction.Behaviors> 
    <GamePad:XboxBehavior StartFocusControlName="continuousList1" IsTopLevelViewForFocus="True"/> 
</i:Interaction.Behaviors> 

<UserControl.Resources> 
    <DataTemplate x:Key="contlisttemplate" > 
     <Button 
      Command="{Binding Gotodetailpage}" 
      Style="{StaticResource custherotile}"> 
     </Button> 
    </DataTemplate> 
</UserControl.Resources> 

<Grid x:Name="LayoutRoot"> 
    <Grid.ColumnDefinitions> 
     <ColumnDefinition/> 
    </Grid.ColumnDefinitions> 
    <Grid.RowDefinitions> 
     <RowDefinition/> 
    </Grid.RowDefinitions> 

    <xbox:ContinuousList 
     HorizontalAlignment="Left" 
     Name="continuousList1" 
     VerticalAlignment="Top"      
     ItemTemplate="{StaticResource contlisttemplate}" 
     ItemsSource="{Binding LongListItems}" Height="316" Width="1280" 
     Grid.Row="1" 
     > 

     <i:Interaction.Behaviors> 
      <GamePad:XboxBehavior IsContinuousListVuiEnabled="True" HasFocusRetention="True"/> 
     </i:Interaction.Behaviors> 

    </xbox:ContinuousList> 

public class LongListViewModel : ViewModelBase<LongListViewModel> 
{ 
    private readonly IDialogService dialogService; 
    public Navigateto compass = new Navigateto(); 

    public LongListViewModel() 
    { 
     LongListItems = new ObservableCollection<object>(); 
     dictionaryListwithkey = new Dictionary<string, object>(); 
     Gotodetailpage = new RelayCommand(PerformGotoDetailPage); 
    } 

    public LongListViewModel(IDialogService dialogService) 
     : this() 
    { 
     this.dialogService = dialogService; 
    } 


    public Program getherovideo 
    { 
     get { return (Program)LongListItems[0]; } 
     set 
     { 
      //SetProperty(ref currentVideo, value,x => x.CurrentVideo); 
     } 
    } 

    public ObservableCollection<object> LongListItems 
    { 
     get; 
     set; 
    } 


    public Dictionary<string, object> dictionaryListwithkey 
    { 
     get; 
     set; 
    } 

    public ICommand Gotodetailpage { get; private set; } 

    private void PerformGotoDetailPage() 
    { 
     // Console.WriteLine("List item clicked"); 
     compass.goToDetailsPageWithPath("89"); 
    } 
} 

回答

0

爲了防止有人想知道答案了。按照Aaron Hill ATG:

這看起來像一個範圍問題。外部DataContext是您的LongListViewModel類,它包含所需的ICommand,但容器的ItemsSource被設置爲由視圖模型公開的LongListItems集合。這意味着DataTemplate的有效DataContext是集合的單獨成員,而不是整個視圖模型。

覆蓋DataTemplate的DataContext會讓您指向視圖模型並訪問ICommand,但這也意味着您會丟失LongListItems集合中各個元素中存在的任何數據。這可能是爲什麼圖像不再適用於這種情況。

由於集合中的每個項目都有自己的按鈕,因此ICommand屬性可能在單個項目上暴露,而不是在視圖模型上顯示。