Binding to viewmodel from inside a datatemplate

后端 未结 2 1015
礼貌的吻别
礼貌的吻别 2020-12-05 18:06

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

相关标签:
2条回答
  • 2020-12-05 18:41
    Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=DataContext.StartVideo}"
    
    0 讨论(0)
  • 2020-12-05 18:41

    Another approach would be to use ElementName binding instead of RelativeSource.

    Example:

    <Window x:Name="root" ... >
    
      ...
    
      Command="{Binding ElementName=root, Path=DataContext.StartVideo}"
    
      ...
    

    A possible advantage over RelativeSource is that this is explicit; if someone changes the XAML hierarchy then relative references could break unintentionally. (Not likely in this specific example of binding to a Window however).

    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.

    0 讨论(0)
提交回复
热议问题