wpf 从数据模板内部绑定到视图模型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18245936/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Binding to viewmodel from inside a datatemplate
提问by Jeroen
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.
我显示了多个视频,它们与 Mainviewmodel 中的视频集合绑定。一切正常,直到我尝试将 enter 命令绑定到 Mainviewmodel。我不知道这个的语法。就目前而言,绑定设置为 Video 而不是 Mainviewmodel。
Errormessage:
错误信息:
'StartVideoCommand' property not found on 'object' ''Video'
Xaml:
Xml:
<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
回答by Jeroen
Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=DataContext.StartVideo}"
回答by UuDdLrLrSs
Another approach would be to use ElementNamebinding instead of RelativeSource.
另一种方法是使用ElementName绑定而不是RelativeSource.
Example:
例子:
<Window x:Name="root" ... >
...
Command="{Binding ElementName=root, Path=DataContext.StartVideo}"
...
A possible advantage over RelativeSourceis if your "root" element already is named, in which case that is easy to take advantage of.
一个可能的优势RelativeSource是如果您的“根”元素已经被命名,在这种情况下很容易利用。
It is also somewhat more readable.
它也更具可读性。

