samedi 9 mai 2015

WPF: Not able to set color in resource through binding

We have our different icons in form of xaml resources in the application something like this:

<ResourceDictionary xmlns="http://ift.tt/o66D3f"
                xmlns:x="http://ift.tt/mPTqtT">
<DrawingBrush x:Key="My_Icon">
    <DrawingBrush.Drawing>
        <GeometryDrawing Brush="Gray"> <!--I want to set this Brush here using binding-->
            <GeometryDrawing.Geometry>
                <GeometryGroup>
                    <EllipseGeometry Center="50,50" RadiusX="45" RadiusY="20" />
                    <EllipseGeometry Center="50,50" RadiusX="20" RadiusY="45" />
                </GeometryGroup>
            </GeometryDrawing.Geometry>
        </GeometryDrawing>
    </DrawingBrush.Drawing>
</DrawingBrush>

And we use these resources in another xaml file (load this resource in code behind, refer to the code below)

<Window x:Class="PracticeWPFApp.Window2"
    xmlns="http://ift.tt/o66D3f"
    xmlns:x="http://ift.tt/mPTqtT"
    Title="Window2" Height="300" Width="300"
    x:Name="MyWindow2">

<Grid>
    <Rectangle Fill="{Binding Path=MyBrush}"/>
</Grid>

code behind:

public partial class Window2 : Window
{
    public Window2()
    {
        InitializeComponent();
        this.DataContext = this;

        var resource = Application.Current.FindResource("My_Icon");
        this.MyBrush = resource as DrawingBrush;
    }

    private DrawingBrush _myBrush;

    public DrawingBrush MyBrush
    {
        get { return _myBrush; }
        set { _myBrush = value; }
    }
}

The issue is, I am not able to set the icon color (in resource code, the first code snippet) using the binding, with property which is in ViewModel (MyBrush property in this case in Window2 code behind)

I tried with following code in resource file:

<GeometryDrawing Brush="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}">

But this isn't working. What I might be missing here.

Aucun commentaire:

Enregistrer un commentaire