[英]Binding to viewmodel from inside a datatemplate
I have multiple videos displayed they are bound with a videocollection in Mainviewmodel.我显示了多个视频,它们与 Mainviewmodel 中的视频集合绑定。 Everything works fine untill I try to bind the enter command to Mainviewmodel.
一切正常,直到我尝试将 enter 命令绑定到 Mainviewmodel。 I Don't know the syntax for this.
我不知道这个的语法。 As it stands the binding is set to Video and not 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
Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=DataContext.StartVideo}"
Another approach would be to use ElementName
binding instead of RelativeSource
.另一种方法是使用
ElementName
绑定而不是RelativeSource
。
Example:例子:
<Window x:Name="root" ... >
...
Command="{Binding ElementName=root, Path=DataContext.StartVideo}"
...
A possible advantage over RelativeSource
is that this is explicit; RelativeSource
一个可能优势是这是明确的; if someone changes the XAML hierarchy then relative references could break unintentionally.如果有人更改了 XAML 层次结构,则相对引用可能会意外中断。 (Not likely in this specific example of binding to a
Window
however). (但是,在绑定到
Window
这个特定示例中不太可能)。
Also if your "root" element already is named then so much the better it is easy to take advantage of.此外,如果您的“根”元素已经被命名,那么它就更容易利用。
It is also somewhat more readable.它也更具可读性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.