标题是我的问题。我将在下面解释。
我正在工作的wpf应用程序是vs2010。我有两个窗口,一个是我的MainWindow窗口,另一个是fileList窗口。在我的fileList窗口中,我有一个文件列表,单击这些文件即可加载该文件。在fileList类中实现了onClick方法。加载文件的函数在MainWindow分部类中实现。
我的fileList类在MainWindow类中实例化以显示窗口。我不能再次实例化MainWidow。MainWindow中的函数(方法)不能被声明为静态的,因为它使用了我不能(不知道如何)声明为静态的其他参数。
我正在粘贴下面的相关代码。请帮帮忙。
namespace test
{
public partial class MainWindow : Window
fileList fl = new fileList;
public MainWindow()
{
InitializeComponent();
fl.show();
}
public void porcessfile(string path)
{
//this method processes the the file at "path". It uses combobox and scrollviewer
//declared in xaml. I dont know how to declare static in xaml, else I will declare
//them static and change the whole method to static, so I can call it without
//instantiating. I tried making a nested-class, but then I can't access variable
//declared in MainWindow (parent) class. Or there is a way to do that?
}
}另一个类:
namespace test
{
public partial class fileList : Window
{
public fileList()
{
IntializeComponent();
}
private void Button_click(object sender, RoutedEventsArgs e)
{
//code that gets "path" on click, works fine.
processfile(string path); // what and how to do here.
}
}
} 我真心希望我说清楚了。如果需要,请询问详细信息。
发布于 2013-07-04 17:10:57
好的,这应该是相当简单的。您只需在FileList类中声明一个事件,该事件将在发送文件路径的Button_click方法中触发,并从MainWindow订阅它,然后使用刚刚收到的参数调用您的processfile方法。
在您的FileList类中:
public event EventHandler<EventArgs<string>> PathReceived = delegate { };将其发布到您的Button_click中。
在你的cosntructor上的MainWindow类中:
this.fileList.PathReceived = (o,args) => this.ProcessFile(args.Value);发布代码:
this.PathReceived(null, new EventArgs<string>(yourPath));编辑:我忘了向您提供EventArgs类(它来自我的一个旧项目)。
public class EventArgs<T> : EventArgs
{
/// <summary>
/// Initializes a new instance of the <see cref="EventArgs{T}"/> class.
/// </summary>
/// <param name="value">The value.</param>
public EventArgs(T value)
{
Value = value;
}
/// <summary>
/// Gets the value.
/// </summary>
/// <value>
/// The value.
/// </value>
public T Value { get; private set; }
}发布于 2013-07-04 16:47:46
嗯,最简单的解决方案是简单地给你的Filelist窗口一个构造函数,这个构造函数接受一个指向Mainwindows中的processfile方法的委托。看看这篇文章:http://www.codeproject.com/Articles/109000/C-Delegates-Step-by-Step
让它变得静态不是解决方案-it将是一个非常丑陋的黑客,这会造成比委托更多的麻烦。
发布于 2013-07-04 16:54:36
您的应用程序中的所有窗口都有一个静态的便捷访问属性:
Application.Current.Windows
然后,只需取第一个类型(如果有多个类型,则找出正确的一个)并转换为您的MainWindow类型。现在你有了一个实例来调用你的方法。
https://stackoverflow.com/questions/17465713
复制相似问题