从数据模板内部绑定到视图模型

32

我有多个视频显示,它们与Mainviewmodel中的一个videocollection绑定。在我尝试将enter命令绑定到Mainviewmodel时,一切都正常运行。我不知道该如何编写语法。目前绑定设置为Video而不是Mainviewmodel。

错误消息:

'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

这个回答解决了你的问题吗?WPF数据绑定:如何访问“父”数据上下文? - StayOnTarget
2个回答

48
Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=DataContext.StartVideo}"

4
我必须绑定到一个命令,因此我这样做: Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type UserControl}}, Path=DataContext.COMMAND_I_WANT_TO_BIND_TO}" - Tono Nam

9
另一种方法是使用ElementName绑定代替RelativeSource
示例:
<Window x:Name="root" ... >

  ...

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

  ...
RelativeSource相比较而言,这种方式更加明确;如果有人更改了XAML层次结构,则相对引用可能会意外中断。(但在绑定到Window的特定示例中不太可能发生)。
此外,如果您的“根”元素已经命名,那么效果会更好,因为可以轻松地利用它。
这种方式也更易读。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接