Search code examples
c#xamlresourcesresourcedictionary

How to use a resource twice?


In my application resources I have:

    <Application.Resources>

    <Border x:Key="border1" BorderBrush="{x:Null}" BorderThickness="0" Height="159"  Width="5" >
        <Border.Background>
            <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                <GradientStop Color="#FFFC0C0C" Offset="0" />
                <GradientStop Color="#63FF0000" Offset="0.999" />
                <GradientStop Color="#6AFE0000" Offset="0.048" />
            </LinearGradientBrush>
        </Border.Background>
    </Border>

</Application.Resources>

I will like to add that border to a stack panel like:

            Border temp = new Border();
            temp = (Border)FindResource("border1");
            temp.Name = "bar" + i;
            stackPanel1.Children.Add(temp);

This works fine. The only problem is that I would like to add two instances of that border. Therefore I have placed that inside a loop:

            for (int i = 0; i < 10; i++)
        {
            Border temp = new Border();
            temp = (Border)FindResource("border1");
            temp.Name = "bar" + i;
            stackPanel1.Children.Add(temp);
        }

on the second iteration I get the error:

enter image description here

But to me there does not seem to be a parse exeption because note how there is no problem on the first iteration:

enter image description here

How could I use a resource several times? I know I could create that resource dynamically but I need to actually use the resource.


Solution

  • If you add x:Shared="false" to your resource definition, it should work:

    <Border x:Key="border1" x:Shared="false" BorderBrush="{x:Null}" BorderThickness="0" Height="159"  Width="5" >
        <Border.Background>
            <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                <GradientStop Color="#FFFC0C0C" Offset="0" />
                <GradientStop Color="#63FF0000" Offset="0.999" />
                <GradientStop Color="#6AFE0000" Offset="0.048" />
            </LinearGradientBrush>
        </Border.Background>
    </Border>