【问题标题】:Binding to viewmodel from inside a datatemplate从数据模板内部绑定到视图模型
【发布时间】:2013-08-17 05:51:21
【问题描述】:

我显示了多个视频,它们与 Mainviewmodel 中的视频集合绑定。一切正常,直到我尝试将输入命令绑定到 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 binding viewmodel datatemplate itemtemplate


【解决方案1】:

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

例子:

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

  ...

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

  ...

相对于RelativeSource 的一个可能优势是它是明确的;如果有人更改 XAML 层次结构,则相对引用可能会意外中断。 (但是,在这个绑定到 Window 的具体示例中不太可能)。

此外,如果您的“根”元素已经命名,那么它就更容易利用了。

它也更具可读性。

【讨论】:

    【解决方案2】:
    Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=DataContext.StartVideo}"
    

    【讨论】:

    • 我必须绑定到一个命令,所以我做了:Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type UserControl}}, Path=DataContext.COMMAND_I_WANT_TO_BIND_TO}"
    猜你喜欢
    • 2013-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多