如何将信息从一个窗口发送到另一个窗口?WPF
本文关键字:窗口 另一个 WPF 一个 信息 | 更新日期: 2023-09-27 18:14:39
如何将信息从一个wpf窗口发送到另一个窗口。我想要的是string filepath
保存它第一次被调用时得到的信息。
这就是问题所在,当我从window1. xml .cs单击button1
时,它从DocumentManager.cs调用openfile()
。当我从window2. xml .cs访问filepath
时,它给出了一个空字符串。我想保存从window1。xml。cs调用时得到的文件路径字符串。
我有:
window1.xmal.cs
DocumentManager mgr = new DocumentManager();
private void Button1_Click(object sender, RoutedEventArgs e) {
ImageSource imgsource = new BitmapImage(new Uri(mgr.openfile().ToString()));
themeImage.Source = imgsource;
}
DocumentManager.cs
public string filePath;
public object openfile() {
OpenFileDialog open = new OpenFileDialog();
bool? result = open.ShowDialog();
if (result == true) {
filePath = open.FileName;
}
return filePath;
}
我认为你的问题是你实例化DocumentManager
类的方式。
我举了一个有效的例子。下面是代码:
主窗口
public partial class MainWindow : Window
{ DocumentManager mgr;
Window2 w2;
public MainWindow() { InitializeComponent(); }
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{ mgr = new DocumentManager(); w2 = new Window2(); w2.Show(); }
private void Button_Click(object sender, RoutedEventArgs e)
{ ImageSource imgsource; string imglocation;
try {
imglocation = mgr.openfile().ToString();
imgsource = new BitmapImage(new Uri(imglocation));
result.Text = imglocation;
w2.imgsource = imgsource;
}
catch (Exception ex)
{ System.Windows.MessageBox.Show(ex.Message); }
}
}
DocumentManager
class DocumentManager
{
public string filePath;
public string openfile()
{
Microsoft.Win32.OpenFileDialog open = new Microsoft.Win32.OpenFileDialog();
bool? result = open.ShowDialog();
if (result == true) { filePath = open.FileName; }
else { filePath = "Nothing Opened"; }
return filePath;
}
}
MainWindow XAML
<Window x:Class="CrossClassDialog.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="120" Width="350" Loaded="MainWindow_Loaded">
<Grid>
<Button Content="Button" HorizontalAlignment="Left" VerticalAlignment="Top" Click="Button_Click"/>
<TextBlock x:Name="result" HorizontalAlignment="Left" Text="TextBlock" VerticalAlignment="Top" Margin="0,30,0,0"/>
</Grid>
</Window>
Window2 XAML
<Window x:Class="CrossClassDialog.Window2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window2" Height="300" Width="300">
<Grid>
<Viewbox HorizontalAlignment="Left" VerticalAlignment="Top">
<Image x:Name="OpenedImage" Source="{Binding ImageSource}" />
</Viewbox>
</Grid>
</Window>
在windows2中添加此属性
private ImageSource _imgsource;
public ImageSource imgsource
{
get { return _imgsource; }
set
{
_imgsource = value;
OpenedImage.Source = value;
}
}
顺便说一下,我改变了一些东西,比如你的openfile()
方法返回的类型。