c# - wpf - 在窗口切换之间刷新图片

时间:2017-03-01 15:07:28

标签: c# wpf image picturebox

我有简单的wpf应用程序,包含2个窗口:MainMenu和PictureWindow。 在MainMenu中,我有一个带有click事件的按钮,它打开了Picture Window:

private void btnOpenPicWindow_Click(object sender, RoutedEventArgs e)
{
    var picWindow = new PictureWindow();
    Application.Current.MainWindow = picWindow;
    Close();
    picWindow.Show();
}

在PictureWindow中,我有WindowsFormsHost PictureBox。在PictureWindow中,我收到了我从另一个应用程序发送的图像,并在PictureBox上显示。 PictureWindow还有一个带有click事件的按钮,可以像这样返回MainMenu:

private void btnBack_Click(object sender, RoutedEventArgs e)
{
    var mMenu = new MainWindow();
    System.Windows.Application.Current.MainWindow = mMenu;
    Close();
    mMenu.Show();
}

当我打开MainWindow然后打开PictureWindow时,一切正常。问题是当我从PictureWindow回到MainMenu然后再回到PictureWindow时,如果我将图片发送到我的PictureBox,它就不会刷新。我收到的图片是因为我在重新布局期间看到它,但我的PictureBox是空白的。

1 个答案:

答案 0 :(得分:0)

每次单击MainWindow上的按钮时,都应尝试使用图片重新初始化窗口。

如果您想使用异步或同步方法加载图片,可以更改LoadAsync Load

WPF PictureWindow:

<Window x:Class="WpfApplication2.PictureWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="PictureWindow" Height="300" Width="300"
        xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms" Loaded="Window_Loaded">
    <Grid>
        <WindowsFormsHost Height="100" HorizontalAlignment="Left" Margin="12,12,0,0" Name="windowsFormsHost1" VerticalAlignment="Top" Width="200">
            <wf:PictureBox x:Name="pbImage" SizeMode="AutoSize"></wf:PictureBox>
        </WindowsFormsHost>
    </Grid>
</Window>

C#PictureWindow:

public partial class PictureWindow : Window
{
    public string imgsrc = string.Empty;
    public PictureWindow()
    {
        InitializeComponent();
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        pbImage.LoadAsync(imgsrc);
    }
}

C#MainWindow:

public partial class MainWindow : Window
{
    PictureWindow window;

    public MainWindow()
    {
        InitializeComponent();
    }
}
private void button1_Click(object sender, RoutedEventArgs e)
{
    window = new PictureWindow();
    window.imgsrc = textBox1.Text.Trim(); //Here you update your "Source" for your image.
    window.Show();
}