里面一个DataTemplate WPF外地产 [英] Outside Property inside a DataTemplate WPF

查看:127
本文介绍了里面一个DataTemplate WPF外地产的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

情景:我有一个列表框和ListBoxItems有一个DataTemplate。我想要做的就是把一个文本菜单中的DataTemplate。美中不足的是,我希望这个文本菜单的ItemsSource为根据窗口的某些属性有所不同。我最初的想法是,我可以在刚才的ItemsSource绑定到属性窗口,然后将返回的ItemsSource;不过,我似乎无法正确地绑定到该属性。我相信这是因为我在DataTemplate中,因此DataContext的(我相信这是正确的字)是一个ListBoxItem,而不是窗口的。 我怎么能得到的ContextMenu这是一个DataTemplate内绑定到一个属性的DataTemplate。

Scenario: I have a ListBox and the ListBoxItems have a DataTemplate. What I want to do is put a ContextMenu in the DataTemplate. The catch is that I want this ContextMenu ItemsSource to be different depending on certain properties in the window. My initial thought is that I could just bind the ItemsSource to a Property in the window and that would return an ItemsSource; however, I cant seem to bind to this property correctly. I believe this is because I am in the DataTemplate and consequently the DataContext (I believe that is the right word) is of that ListBoxItem and not of the window. How could I get the ContextMenu that is inside a DataTemplate to bind to a Property outside of the DataTemplate.

推荐答案

您可以通过使用的RelativeSource FindAncestor语法获得的DataContext从窗口

You can get the DataContext from your window by using the RelativeSource FindAncestor syntax

<DataTemplate>
  <TextBlock Text="{Binding MyInfo}">
    <TextBlock.ContextMenu>
      <Menu ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.MyContextMenuItems}"/>
    </TextBlock.ContextMenu>
  </TextBlock>
</DataTemplate>

不能完全确定,但结合是正确的? 如果您的DataContext是另一个对象的类型,你只需要改变AncestorType(例如,通过用户控件)。

Not totally sure, but the binding is correct... If your DataContext is on another object type, you just have to change the AncestorType (eg. by UserControl).

这篇关于里面一个DataTemplate WPF外地产的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆