2012-07-06 131 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属性可能在单个项目上暴露,而不是在视图模型上显示。