3

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;
}
Yair V.
  • 109
  • 1
  • 10
  • Not sure I find the exception message. – Janis S. Jan 25 '17 at 11:51
  • Wouldn't an [ImageBrush](https://msdn.microsoft.com/en-us/library/system.windows.media.imagebrush(v=vs.110).aspx) be what you are looking for? – wkl Jan 25 '17 at 11:56
  • Actually, I prefer the original version to the edited one. You are actually converting an Image, not an object. The fact that `MenuItem.Icon` is an `object` is just a technical detail IMO. In fact, this edit might even change the meaning of the question. I think other people may easier find this post by its original title. But maybe that's just me... – wkl Jan 25 '17 at 12:47

2 Answers2

2

You can create an ImageBrush from your image.

private void BackgroundMenuItem_Switch(MenuItem sender, RoutedEventArgs e)
{
    this.Background = new ImageBrush(((Image)(sender.Icon)).Source);
}
wkl
  • 1,896
  • 2
  • 15
  • 26
  • Thank you so much! (and everyone else too), it seems that for some reason the MenuItem.Icon is being treated as an object, which has got no .Source property. Hence I used `this.Background = new ImageBrush(((Image)(sender.Icon)).Source);` – Yair V. Jan 25 '17 at 12:05
  • @Yair Yes, `MenuItem.Icon` is of type `object`. I missed that. I have updated my answer to include the cast.. – wkl Jan 25 '17 at 12:10
1

You could use an ImageBrush:

<Window ...>
    <Window.Background>
        <ImageBrush ImageSource="img/0.png" />
    </Window.Background>
    ...
</Window>

Background = new ImageBrush() { ImageSource = new BitmapImage(new Uri("img/1.png", UriKind.RelativeOrAbsolute)) };

Or if you are using an image resource, use a pack URI:

Background = new ImageBrush() { ImageSource = new BitmapImage(new Uri("pack://application:,,,/img/x.png", UriKind.RelativeOrAbsolute)) };
mm8
  • 163,881
  • 10
  • 57
  • 88