如何在ItemContainerStyle的样式设置器中绑定到特定的Item属性?

时间:2018-08-13 23:16:10

标签: wpf xaml

我有一个问题,该问题没有破坏我的代码中的任何内容,它只是引起一堆令人讨厌的警告和花在解析绑定表达式上的时间。我想解决它。

具体来说,这是我收到的警告之一:

  

System.Windows.Data错误:2:找不到管理FrameworkElement   或FrameworkContentElement作为目标元素。   BindingExpression:Path =颜色; DataItem = null;目标元素是   'SolidColorBrush';目标属性为“颜色”(类型为“颜色”)

(对于Opacity和DashStyle,我又得到了两个,但是为了简洁起见,我将继续使用颜色来回答这个问题。)

以下是相关代码:

<z:ClassWithMyItems ItemsSource="{Binding Items}">
   <z:ClassWithMyItems.ItemContainerStyle>
        <Style TargetType={"x:Type z:MyItem}">
            <Setter Property="Pen">
                <Setter.Value>
                    <Pen Thickness="2.0" options:Freeze="True" DashStyle="{Binding DashStyle}">
                        <Pen.Brush>
                            <SolidColorBrush Color={Binding Color, Converter={StaticResource ColorConverter}}" Opacity="{Binding Opacity}" />
                        </Pen.Brush>
                    </Pen>
                </Setter.Value>
            </Setter>
        </Style>
    </z:Feature.ItemContainerStyle>
</z:ClassWithMyItems>

(注意:DataContext设置为MyClassWithItems的实例,该实例具有一组“ Items”,并且每个Item具有“ Color”属性)。

据我所知,xaml首先在 SolidColorBrush 的DataContext中查找,并抱怨它为空。然后,经过几次尝试,它最终决定查看 Item 的DataContext,并在其上找到'Color'属性并停止抱怨。 (我知道这一点,因为它最终可以正确解析并呈现)。

如果知道先查看'Item'的DataContext而不是SolidColorBrush的话,可以节省很多工作。对于我的一生,我不知道该怎么做。

有什么建议吗?谢谢!

1 个答案:

答案 0 :(得分:1)

如@Clemens所建议,您可以使用返回Pen的转换器。只需绑定到MyItem对象本身即可:

public class PenConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        MyItem myItem = value as MyItem;
        if (myItem == null)
            return value;

        Pen pen = new Pen();
        pen.DashStyle = myItem.DashStyle;
        pen.Brush = myItem.Brush;
        //...
        pen.Freeze();
        return pen;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

XAML:

<Style TargetType="{x:Type z:MyItem}">
    <Style.Resources>
        <local:PenConverter x:Key="converter" />
    </Style.Resources>
    <Setter Property="Pen" Value="{Binding Path=., Converter={StaticResource converter}}" />
</Style>