首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >从数据模板内部绑定到视图模型

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

Stack Overflow用户
提问于 2013-08-15 11:32:52
回答 2查看 15.7K关注 0票数 29

我有多个视频显示,它们与Mainviewmodel中的视频集合绑定。在我尝试将enter命令绑定到Mainviewmodel之前,一切都运行正常。我不知道这个的语法。现在,绑定设置为Video,而不是Mainviewmodel。

错误消息:

代码语言:javascript
复制
'StartVideoCommand' property not found on 'object' ''Video'   

Xaml:

代码语言:javascript
复制
<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
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-08-23 08:02:29

代码语言:javascript
复制
Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=DataContext.StartVideo}"
票数 41
EN

Stack Overflow用户

发布于 2020-05-02 03:45:22

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

示例:

代码语言:javascript
复制
<Window x:Name="root" ... >

  ...

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

  ...

RelativeSource相比,一个可能的优点是这是显式的;如果有人更改了XAML层次结构,则相对引用可能会在无意中中断。(但是,在绑定到Window的这个特定示例中不太可能)。

另外,如果你的“根”元素已经被命名了,那么利用起来就更容易了。

它的可读性也更好一些。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18245936

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档