VisualBrush not rendering in Style

Why would my VisualBrush render a lovely image in my button with this code:

<Button>
    <Rectangle Width="28" Height="28">
        <Rectangle.Fill>
            <VisualBrush Stretch="Fill" Visual="{StaticResource lovely_image}" />
        </Rectangle.Fill>
    </Rectangle>
</Button>

But render nothing with this code?:

<Button>
    <Rectangle Width="28" Height="28">
        <Rectangle.Style>
            <Style TargetType="{x:Type Rectangle}">
               <Setter Property="Fill">
                    <Setter.Value>
                        <VisualBrush Stretch="Fill" Visual="{StaticResource lovely_image}" />                               
                    </Setter.Value>
                </Setter>
            </Style>
        </Rectangle.Style>
    </Rectangle>
</Button>

Interestingly, if I replace the VisualBrush in the second example with a SolidColorBrush, the SolidColorBrush renders.

(Why am I doing this? I'm trying to use DataTriggers to swap icons based on values in my ViewModel.)

Update

So it seems that this code works just fine. My problem was actually some weirdness in the way my resources which define my visual. The visual used a brush dynamic resource which was being loaded from a referenced assembly. This worked with the first example above, but for some reason wouldn't for the second example. I just copied the brush into a resource in my projects assembly and viola!, my lovely_image is rendered.

Answers


A SolidColorBrush is abstract and can be used in multiple places. A visual is not, it can only have one parent.

You can try x:Shared="false" on the visual in the resources. Or use the Button.ContentTemplate to make the button create multiple Rectangles (inline the visual & Content needs to be set to something for it to apply).

Also if this is not about multiple instances as the code in your question is fine: Mind dependency property value precedence.


Need Your Help

It is possible to add 'None' option in ajax toolkit calendar extender?

asp.net calendarextender

I have an &lt;ajaxToolkit:CalendarExtender&gt; object in my page. It puts the selected date on a disabled TextBox (populated at start with the today date).

Azure Website Connection to a ServiceBus Queue remote name could not be resolved

c# azure message-queue servicebus

I have a simple Azure website (PaaS website) that is trying to connect to a Service Bus queue. However, it is getting the error: