从数据模板中绑定到viewmodel。

问题描述 投票:25回答:2

我有多个视频显示,它们与Mainviewmodel中的videocollection绑定。一切都很好,直到我尝试将enter命令绑定到Mainviewmodel。我不知道这个语法。目前,绑定是设置为视频而不是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 binding viewmodel datatemplate itemtemplate
2个回答
38
投票
Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=DataContext.StartVideo}"

2
投票

另一种方法是使用 ElementName 绑定而不是 RelativeSource.

例如:

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

  ...

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

  ...

一个可能的优势是 RelativeSource 是,这是显式的;如果有人改变了XAML层次结构,那么相对引用可能会无意中中断。(在这个绑定到一个 Window 然而)。)

另外,如果你的 "根 "元素已经被命名,那么就更好了,很容易利用。

它的可读性也更强一些。

© www.soinside.com 2019 - 2024. All rights reserved.