Arizona1911
Arizona1911

Reputation: 2201

Silverlight Setting attribute of Rectangle

I have a rectangle that looks like this

<Rectangle x:Name="rect" 
           Width="76" Height="76"
           HorizontalAlignment="Left">
    <Rectangle.Fill>
        <ImageBrush x:Name"image" ImageSource="Media/Tile_01.png"/>
    </Rectangle.Fill>
    <Rectangle.RenderTransform>
        <TranslateTransform x:Name="rectTranslateTransform" X="0" Y="0" />
    </Rectangle.RenderTransform>
</Rectangle>

How do I set the ImageSource attribute of ImageBrush in the .cs file? Is there a way to get the child of rect?

Upvotes: 1

Views: 745

Answers (2)

AnthonyWJones
AnthonyWJones

Reputation: 189457

This works:-

image.ImageSource = new BitmapImage(new Uri("/Media/Tile_02.png", UriKind.Relative));

Some things to consider, the source pngs are they 76x76 already? If not consider storing a set at that resolution, scaling large images down still requires the original large image to remain in mem and that can be costly.

If you re-use the images for the tiles then it might be better for you to build a dictionary of ImageBrush and assign them directly to the Fill property of the rectangles.

It might also be reasonable to question why you are using a rectangle at all? Why not a straight forward Image control?

Upvotes: 1

ColinE
ColinE

Reputation: 70142

The ImageBrush isn't actually a child of the Rectangle in the same sense that a Button can be a child of a Grid. The Rectangle.Fill element is using property element syntax, see the following link:

http://msdn.microsoft.com/en-us/library/bb412392.aspx#settingproperties

Therefore, you can tell from the XAML that Rectangle has a Fill property. Looking at the documentation for Shape.Fill you can see that this is of type Brush:

http://msdn.microsoft.com/en-us/library/system.windows.shapes.shape.fill.aspx

Therefore you will have to cast it to ImageBrush. The complete code is:

Brush fill = rect.Fill;
ImageBrush imageBrush = fill as ImageBrush;

// set the source
imageBrush.Source = new BitmapImage(new Uri("/MyNameSpace;images/someimage.png", UriKind.Relative));

Upvotes: 1

Related Questions