【问题标题】:How to bind to a different datacontext then the inherited one for the style value?如何绑定到不同的数据上下文,然后为样式值绑定继承的数据上下文?
【发布时间】:2015-08-01 06:38:58
【问题描述】:

而不是使用多个带有 MulitBinding 的 DataTrigger 来设置 ListViewItem 的背景颜色:

 <DataTrigger Value="4" >
                <DataTrigger.Binding>
                    <MultiBinding Converter="{StaticResource WaitStatus}">
                        <Binding Path="Checkin" />
                        <Binding Path="Checkout" />
                        <Binding Path="Notseen" />
                    </MultiBinding>
                </DataTrigger.Binding>
                <Setter Property="Background" Value="{StaticResource GreenBrush}" />
            </DataTrigger>

我正在尝试使用附加属性返回 ListViewItem 背景的画笔颜色。代码如下所示:

<Style x:Key="listViewItemStyle" TargetType="{x:Type ListViewItem}">
        <Setter Property="v:ListViewItemBehavior.MyValue" Value="{Binding testvalue}"/>
        <Setter Property="Background" Value="{Binding Path=(v:ListViewItemBehavior).Background}" />

我的目标是让第一个 setter 将 ListViewItem 的 DataContext 传递到 v:ListViewItemBehavior.MyValue 处的附加属性。然后附加属性计算背景颜色并将结果放在 ListViewItemBehavior.Background 中。

然后第二个设置器是从 ListViewItemBehavour 中提取背景颜色并从中设置 ListViewItem 的背景颜色。

附加属性 ListViewItemBehaviour 可以正确设置背景颜色,但我不知道如何将此颜色返回给第二个设置器的 XAML。第二个 setter 中值的 {Binding...} 总是在 ListViewItem 的 DataContext 中查找 v:ListViewItemBehavior - 我无法让它在 ListViewItemBehaviour 中查找背景颜色。

如何为 Setter Value 属性使用不同的数据上下文,然后从 ListViewItem 继承数据上下文? (请使用语法)。

TIA

【问题讨论】:

    标签: wpf xaml binding attached-properties


    【解决方案1】:

    将Binding的RelativeSource设置为Self,即样式化的ListViewItem:

    <Setter Property="Background"
        Value="{Binding Path=(v:ListViewItemBehavior).Background,
                        RelativeSource={RelativeSource Self}}" />
    

    【讨论】:

    • 事实证明,Background 是 ListViewItem 的依赖属性,因此如果从附加行为中更改背景,则不需要显式设置器。 :)
    猜你喜欢
    • 2015-07-25
    • 2016-05-23
    • 1970-01-01
    • 1970-01-01
    • 2015-07-04
    • 2013-01-04
    • 2016-04-28
    • 2018-07-18
    • 1970-01-01
    相关资源
    最近更新 更多