C # - convert object to brush (WPF)

I am trying to set my Mainwindow background [via the MenuItem control] using MenuItem.Icon. The problem is that MenuItem.Icon is an object , and Mainwindow.Background is Brush (or Brush Control). Is there a way to convert between the two? I tried BrushConverter.ConvertFrom, but it cannot convert Image objects (this is the exception message shown). Thank you Here is some XAML code:

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

and here the code is 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;
}
+4
source share
2 answers

You can create an ImageBrush from your image.

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

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)) };

, , URI :

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

Source: https://habr.com/ru/post/1667755/


All Articles