我有2个窗口,当在第一个窗口上单击按钮时,将出现第二个窗口,提示用户选择/上传图像。所有相关的XAML对象都已创建并设置样式。
问题:如何从第二个窗口获取源文件的字符串值以显示在第一个窗口的文本块中?
Open Window&获取sourceFile代码的字符串值:
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 :(得分:0)
您可以在AddImage类中声明一个公共变量,并在第一个窗口中获取它。