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
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:
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.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.