2017-03-03 96 views
1

我有2個窗口,當第一個窗口上的按鈕被點擊時,第二個窗口會出現,提示用戶選擇/上傳圖像。所有相關的XAML對象都被創建和設計。將字符串從1個窗口傳遞到另一個窗口 - XAML

問題:如何從第二個窗口獲取源文件的字符串值以顯示在第一個窗口的文本塊中?

打開窗口&獲取字符串的資源文件代碼的價值:

 private void btn_Image_Click(object sender, RoutedEventArgs e) 
    { 
     // Create the window 
     AddImage AddImageScreen = new AddImage(); 
     AddImageScreen.Owner = this; 
     // Open and show the window 
     AddImageScreen.ShowDialog(); 

     txtblock_ImgAddress = // How do I get the image source file here? 
    } 

選擇/上傳圖片代碼:

 public partial class AddImage : Window 
{ 

    string imageDirectory; 

    public AddImage() 
    { 
     InitializeComponent(); 
    } 

    private void button_Click(object sender, RoutedEventArgs e) 
    { 

     Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); 
     dlg.Filter = "Images (*.JPG;*.JPEG;*.PNG) | *.JPG;*.JPEG;*.PNG"; 
     Nullable<bool> result = dlg.ShowDialog(); 

     string sourceFile = ""; 
     string fileName = ""; 

     if (result == true) 
     { 
      sourceFile = dlg.FileName; 
      fileName = sourceFile.Substring(sourceFile.LastIndexOf('\\')); 
      var SourceFile = sourceFile; 

     } 

     string destinationFile = imageDirectory + fileName; 

     File.Copy(sourceFile, destinationFile); 

     GetFilesInDirectory(); 
    } 

    private void Window_Loaded(object sender, RoutedEventArgs e) 
    { 
     SetImageDirectory(); 
     GetFilesInDirectory(); 
    } 

    private void GetFilesInDirectory() 
    { 
     // Populate images in selection box 

     lbxFiles.ItemsSource = null; 

     string[] images = Directory.GetFiles(imageDirectory); 
     string[] fileNames = new string[images.Length]; 

     for (int i = 0; i < images.Length; i++) 
     { 
      fileNames[i] = images[i].Substring(images[i].LastIndexOf('\\') + 1); 
     } 

     lbxFiles.ItemsSource = fileNames; 
    } 

    private void SetImageDirectory() 
    { 
     // Set the directions to get into images 
     string currentDirectory = Directory.GetCurrentDirectory(); 

     DirectoryInfo parent = Directory.GetParent(currentDirectory); 

     DirectoryInfo grandparent = parent.Parent; 

     currentDirectory = grandparent.FullName; 

     imageDirectory = currentDirectory + "\\images"; 
    } 

    private void lbxFiles_SelectionChanged(object sender, SelectionChangedEventArgs e) 
    { 
     // open selected file 
     string fileName = lbxFiles.SelectedItem as string; 

     if (fileName != null) 
     { 
      imgAnimal.Source = new BitmapImage(new Uri(imageDirectory + "\\" + fileName, UriKind.Absolute)); 

     } 
    } 

    private void btn_Save_Click(object sender, RoutedEventArgs e) 
    { 

    } 

回答

0

你可以聲明在AddImage類中的公共變量,並把它在第一個窗口。

+0

有沒有AddImage類,只是XAML和XAML.CS – Legend

+0

夥計,'公共部分類AddImage'是你的AddImage類 –

+0

我已經重新工作它只顯示在第二個窗口,但我遇到了由mainWindow上的Image不會通過路徑 – Legend

相關問題