Subhamoy
Subhamoy

Reputation: 116

Convert a Grid element to Image in WPF

I have a code snippet which is currently returned as Grid.

private Grid GetImage(PlacemarkList locationDetail)
{
    Grid gridPushPin = new Grid();
    ImageBrush img = new ImageBrush();
    img.ImageSource = locationDetail.preferredCashback.Equals("1") ? new BitmapImage {         
                           UriSource = Constants.CashbackIconUri,
                           DecodePixelWidth = 36, 
                           DecodePixelHeight = 59 
                       } : new BitmapImage {
                           UriSource = Constants.ATMIconUri, 
                           DecodePixelWidth = 36, DecodePixelHeight = 59
                       };
    TextBlock IndexText = new TextBlock();
    IndexText.TextAlignment = TextAlignment.Center;
    IndexText.Text = locationDetail.IndexNum.ToString();
    gridPushPin.Background = img;
    gridPushPin.Tag = locationDetail.bankAddress;
    gridPushPin.Tap += grid_Tap;
    return gridPushPin;
}

But I want to return the Grid as a Image(Convert the Grid I am generating to Image). Can anybody please help how to accomplish that.

Upvotes: 1

Views: 2133

Answers (4)

iop
iop

Reputation: 312

public class MyWrapperClass
{
    private DataGrid dataGrid;

    public MyWrapperClass(DataGrid grid)
    {
        this.dataGrid = grid;

    }

    public DataGrid MyGrid
    {
        get
        {
            return this.grid;
        }

        set
        {
            this.grid = value;
        }
    }

    public ImageBrush MyImageBrush
    {
        get 
        { 
            this.grid.Background as ImageBrush;
        }

        set 
        { 
            this.grid.Background = value; 
        }
    }
}

Upvotes: 0

Ugur
Ugur

Reputation: 1256

Hey did you check this subject. I think what you need is here.

How do I save all content of a WPF ScrollViewer as an image

Upvotes: 0

Gigi
Gigi

Reputation: 29421

You are creating a Grid, so you will return a Grid.

Create an image instead. Something like:

Image image = new Image();
image.Source = "myImageURL";

This is from memory so actual code may vary depending on what you need to do exactly.

Basically the Source of the image needs to be set similarly to how you're setting ImageSource in your current code, but you may opt to use pack URLs to use an image stored as a resource instead.

Edit after clarifications in comments: So you want to get the grid control as an image. This answer should help.

Upvotes: -1

Sheridan
Sheridan

Reputation: 69959

You can use a VisualBrush to paint a copy of any UIElement onto any other. How about something like this:

<Rectangle Width="150" Height="150">
    <Rectangle.Fill>
        <VisualBrush Visual="{Binding ElementName=NameOfYourGrid}" />
    </Rectangle.Fill>
</Rectangle>

Upvotes: 2

Related Questions