如何从Xaml中的Style中提取Setter value属性?

时间:2016-03-23 14:35:36

标签: c# wpf xaml

我有一个样式具有名为“Fill”的setter属性,并将DrawingBrush作为其值。我想从中提取DrawingBrush以在viewmodel中使用。这是我的风格。

<Style x:Key="ICON_STYLE" TargetType="Rectangle">
    <Setter Property="Fill">
        <Setter.Value>
            <DrawingBrush Viewbox="0,0,39.125,39.125" ViewboxUnits="Absolute">
                <DrawingBrush.Drawing>
                    <GeometryDrawing Brush="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=uiEntityViews:ViewModel}, Path=MeSiteColor}" Geometry="F1M19.5625,0.999954C29.8144,0.999954 38.125,9.31053 38.125,19.5625 38.125,29.8142 29.8143,38.1249 19.5625,38.1249 9.31073,38.1249 1,29.8142 1,19.5625 1,9.31053 9.31064,0.999954 19.5625,0.999954z">
                        <GeometryDrawing.Pen>
                            <Pen DashCap="Square" EndLineCap="Flat" LineJoin="Round" MiterLimit="10" StartLineCap="Flat" Thickness="2">
                                <Pen.Brush>
                                    <LinearGradientBrush EndPoint="0.849422,0.849423" StartPoint="0.150577,0.150578">
                                        <GradientStop Color="#FF657783" Offset="0"/>
                                        <GradientStop Color="White" Offset="0.146"/>
                                        <GradientStop Color="#FF2C4758" Offset="1"/>
                                    </LinearGradientBrush>
                                </Pen.Brush>
                                <Pen.DashStyle>
                                    <DashStyle/>
                                </Pen.DashStyle>
                            </Pen>
                        </GeometryDrawing.Pen>
                    </GeometryDrawing>
                </DrawingBrush.Drawing>
            </DrawingBrush>
        </Setter.Value>
    </Setter>
</Style>

我想提取DrawingBrush如下 -

if (resourceObject is Style)
{
    Style iconStyle = resourceObject as Style;
    var collections = iconStyle.Setters;
    // How to extract iconBrush from collections????
    DrawingBrush iconBrush = ???
}

1 个答案:

答案 0 :(得分:3)

以下可能有效:

DrawingBrush iconBrush = GrabFirstDrawingBrushInStyle(resourceObject as Style);

private DrawingBrush GrabFirstDrawingBrushInStyle(Style style)
{
    if (style != null)
    {
        foreach (var setter in style.Setters.OfType<Setter>())
        {
            if (setter.Value is DrawingBrush)
                return (DrawingBrush)setter.Value;
        }
    }
    return null;
}