WPF"静态"在列表绑定 [英] WPF "static" binding in a List

查看:237
本文介绍了WPF"静态"在列表绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表绑定的一个问题。

I have a problem with a binding in a List.

我有对象的列表。此列表绑定到一个列表框。在我的列表中的每个对象的我可以打开一个文本菜单:

I have a List of objects. This List is bound to a ListBox. Of every object in my List I can open a ContextMenu:

<ListBox.ItemContainerStyle>
  <Style TargetType="ListBoxItem">
    <Setter Property="ContextMenu">
      <Setter.Value>
        <ContextMenu>
          <MenuItem Header="First"  IsEnabled="{Binding FirstEnabled}"/>
          <MenuItem Header="Second"  IsEnabled="{Binding SecondEnable}"/> 
        </ContextMenu>
      </Setter.Value>
    </Setter>
  </Style>
</ListBox.ItemContainerStyle>

在code这样我在列表中的对象有两个布尔绑定。现在我想这两布尔不绑定的对象。我想绑定静态我的DataContext。这不是这样工作,我不知道如何去实现它。

In the code like this my objects in the list having the two booleans to bind. Now I want to bind this two booleans not to the objects. I want to bind it "static" to my DataContext. This is not working like this and I have no idea how to realize it.

我GOOGLE了很多,但没有发现任何有用...

I googled a lot but found nothing helpful ...

感谢您的帮助!

推荐答案

由于文本菜单适用于 ListBoxItem的它将其的DataContext 值和 ListBoxItem的将其 PlacementTarget 。所以,如果你要绑定到 ListBox.DataContext 财产需要传递电流 ListBox.DataContext ,例如,标签 ListBoxItem的,然后你需要从文本菜单通过其 PlacementTarget 。这都是因为文本菜单使用弹出其中<一个href=\"https://msdn.microsoft.com/en-us/library/vstudio/ms749018(v=vs.100).aspx#PopupandtheVisualTree\"相对=nofollow>创建自己的可视树这么简单的RelativeSource / 的ElementName 绑定不会工作

Since, ContextMenu applies to ListBoxItem it will have its DataContext value and ListBoxItem will be its PlacementTarget. So if you want to bind to property of ListBox.DataContext you need to pass current ListBox.DataContext as, for example, Tag to ListBoxItem and then you need to refer to it from ContextMenu via its PlacementTarget. It's all because ContextMenu uses Popup which creates its own visual tree so simple RelativeSource/ElementName binding won't work

<Style TargetType="ListBoxItem">
    <Setter Property="Tag" Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type ListBox}}, Path=DataContext}"/>
    <Setter Property="ContextMenu">
        <Setter.Value>
            <ContextMenu>
                <MenuItem Header="First"  IsEnabled="{Binding RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}, Path=PlacementTarget.Tag.FirstEnabled}"/>
                <MenuItem Header="Second" IsEnabled="{Binding RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}, Path=PlacementTarget.Tag.SecondEnable}"/>                    
            </ContextMenu>
        </Setter.Value>
    </Setter>
</Style>

这篇关于WPF&QUOT;静态&QUOT;在列表绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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