【问题标题】:How to bind with a relative source that is Ancestor and Self?如何与祖先和自我的相对来源绑定?
【发布时间】:2014-02-17 17:45:02
【问题描述】:

我有以下代码:

<ItemsControl ItemsSource="{Binding MyDictionary}" >
<Image Width="16">
    <Image.Style>
        <Style TargetType="{x:Type Image}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding Value}" Value="False">
                    <Setter Property="Source" Value="{Binding RelativeSource =                 
                    {RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}, 
                    Path=DataContext.SecDic}"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding Value}" Value="True">
                    <Setter Property="Source" Value="{Binding RelativeSource =                 
                    {RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}, 
                    Path=DataContext.ThirdDic}"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Image.Style>
</Image>
</ItemsControl>

MyDictionary - 键是枚举类型的字典 现在,如果我将 SecDic 和 ThirdDic 从字典更改为 BitmapImages,则此绑定有效。但我希望 MyDictionary 中的每个键(枚举)都有不同的真/假图像。 所以我试着写:

<Setter Property="Source" Value="{Binding Path=DataContext.SecDic[Key],
                      RelativeSource={AncestorType={x:ItemsControl}}}"/>

但它不起作用,因为“键”属于图像的数据上下文(MyDictionary),我将相对源更改为项目控件,因此没有“键”。 有什么建议吗?

【问题讨论】:

  • RelativeSource的设计不正确,试试这个:"{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}, Path=DataContext.SecDic[Key]}"
  • 是的,对不起,我忘了添加。我这样做了,但它不起作用。生病编辑我的问题

标签: c# wpf binding datacontext relativesource


【解决方案1】:

我为解决这个问题所做的是多绑定 + 自定义多绑定转换器。 字典有一个绑定,键有一个绑定。

【讨论】:

    猜你喜欢
    • 2020-11-07
    • 2021-08-27
    • 1970-01-01
    • 2012-02-05
    • 2011-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-25
    相关资源
    最近更新 更多