Search code examples
c#.netwpfimagebrush

C# - convert Object to Brush (WPF)


I'm trying to set my Mainwindow's Background [through MenuItem control], using the MenuItem.Icon. The problem is MenuItem.Icon is an object, whilst Mainwindow.Background is a Brush (or Brush Control) type. Is there a way to convert between these two? I've tried BrushConverter.ConvertFrom, but it can't convert Image objects (that's the shown Exception message). Thanks! Here's some XAML code:

<MenuItem Header="Waterfall" Click="BackgroundMenuItem_Click">
                            <MenuItem.Icon>
                                <Image Source="images/backgrounds/Waterfall.jpg"/>
                            </MenuItem.Icon>
                        </MenuItem>

and here's the code behind:

//switch background:
//event
private void BackgroundMenuItem_Click(object sender, RoutedEventArgs e)
{
    try
    {
        BackgroundMenuItem_Switch((MenuItem)sender, e);
    }
    catch(Exception exc)
    { MessageBox.Show(exc.Message); }
}
//switch func
private void BackgroundMenuItem_Switch(MenuItem sender, RoutedEventArgs e)
{
    var converter = new BrushConverter();
    var brush = converter.ConvertFrom(sender.Icon);
    this.Background = (Brush)brush;
}

Solution

  • You can create an ImageBrush from your image.

    private void BackgroundMenuItem_Switch(MenuItem sender, RoutedEventArgs e)
    {
        this.Background = new ImageBrush(((Image)(sender.Icon)).Source);
    }