31

I have multiple videos displayed they are bound with a videocollection in Mainviewmodel. Everything works fine untill I try to bind the enter command to Mainviewmodel. I Don't know the syntax for this. As it stands the binding is set to Video and not Mainviewmodel.

Errormessage:

'StartVideoCommand' property not found on 'object' ''Video'   

Xaml:

<Window.Resources>
  <local:MainViewModel x:Key="MainViewModel"/>
</Window.Resources>
  <Grid DataContext="{StaticResource MainViewModel}">
    <ListBox ItemsSource="{Binding Videos}">
      <ListBox.ItemTemplate>
        <DataTemplate>
          <Grid>
            <Grid.InputBindings>

!!!           <KeyBinding Key="Enter" Command="{Binding StartVideo}" /> !Bound to Video not to Mainviewmodel grrr  

            </Grid.InputBindings>
             ... layout stuff
              <TextBlock Text="{Binding Title}" Grid.Column="0" Grid.Row="0" Foreground="White"/>
              <TextBlock Text="{Binding Date}" Grid.Column="0" Grid.Row="1" Foreground="White" HorizontalAlignment="Left"/>
              <TextBlock Text="{Binding Length}" Grid.Column="1" Grid.Row="1" Foreground="White" HorizontalAlignment="Right"/>
             ... closing tags
Jeroen
  • 881
  • 1
  • 7
  • 9
  • Does this answer your question? [WPF Databinding: How do I access the "parent" data context?](https://stackoverflow.com/questions/1127933/wpf-databinding-how-do-i-access-the-parent-data-context) – StayOnTarget Mar 03 '21 at 14:04

2 Answers2

47
Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=DataContext.StartVideo}"
Jeroen
  • 881
  • 1
  • 7
  • 9
  • 4
    I had to bind to a command therefore I did: `Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type UserControl}}, Path=DataContext.COMMAND_I_WANT_TO_BIND_TO}"` – Tono Nam Nov 19 '14 at 19:52
7

Another approach would be to use ElementName binding instead of RelativeSource.

Example:

<Window x:Name="root" ... >

  ...

  Command="{Binding ElementName=root, Path=DataContext.StartVideo}"

  ...

A possible advantage over RelativeSource is that this is explicit; if someone changes the XAML hierarchy then relative references could break unintentionally. (Not likely in this specific example of binding to a Window however).

Also if your "root" element already is named then so much the better it is easy to take advantage of.

It is also somewhat more readable.

StayOnTarget
  • 11,743
  • 10
  • 52
  • 81