2017-03-01 101 views
0

我有簡單的wpf應用程序,它由2個窗口組成:MainMenu和PictureWindow。 在MainMenu的我有click事件一個按鈕,打開圖片窗口:c# - wpf - 在窗口切換之間刷新圖片

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

在PictureWindow我WindowsFormsHostPictureBox。在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(); 
} 

一切正常,當我打開主窗口,然後PictureWindow。問題是,當我從PictureWindow返回到MainMenu,然後再次到PictureWindow,並且如果我發送圖片到我的PictureBox它不會刷新。我收到的圖像,因爲我在debbuging中看到它,但我的PictureBox是空白的。

回答

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#主窗口:

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