UWP Databinding: How to set button command to parent DataContext inside DataTemplate

后端 未结 3 709
灰色年华
灰色年华 2021-01-12 09:14

Short explanation of need: I need to fire the command of a button inside a DataTemplate, using a method from the DataContext of the ViewModel.

Short explanation of p

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-12 10:04

    It really is unfortunate that there is no ancestor binding in UWP. This makes scenarios like yours much more difficult to implement.

    The only way I can think of is to create a DependencyProperty for ViewModel on your Page:

    public ChooseStoryToPlay_ViewModel ViewModel
    {
        get { return (ChooseStoryToPlay_ViewModel)GetValue(ViewModelProperty); }
        set { SetValue(ViewModelProperty, value); }
    }
    
    public static readonly DependencyProperty ViewModelProperty =
        DependencyProperty.Register("ViewModel", typeof(ChooseStoryToPlay_ViewModel), typeof(MainPage), new PropertyMetadata(0));
    

    Now you can bind to it from your data template:

    
        
    
    

    A couple of things to notice:

    • In CommandParameter I assumed that in your Story class there is a Page property that you want to pass as a parameter to your command. You can bind to any other property of Story class here or the class itself.
    • You have to set the name of your page to Page (x:name="Page"), so that you can reference it using ElementName in the data template.
    • I assumed that the command you're calling on the ViewModel is named NavigateCommand and accepts a parameter of the same type as the property bound to CommandParameter:

      public ICommand NavigateCommand { get; } = 
          new RelayCommand(name => Debug.WriteLine(name));
      

    I hope this helps and is applicable to your scenario.

提交回复
热议问题