C# - 将对象转换为画笔(WPF)

时间:2017-01-25 11:49:02

标签: c# .net wpf image brush

我尝试使用MenuItem.Icon设置主窗口的背景[通过MenuItem控件]。问题是MenuItem.Icon是对象,而Mainwindow.Background是 Brush (或Brush Control)类型。 有没有办法在这两者之间进行转换?我已经尝试过BrushConverter.ConvertFrom,但它无法转换Image对象(即显示的Exception消息)。谢谢!这是一些XAML代码:

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

以及后面的代码:

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

2 个答案:

答案 0 :(得分:2)

您可以从图片中创建ImageBrush

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

答案 1 :(得分:1)

您可以使用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)) };