WPF获取父窗口窗口、WPF

由网友(一个人独守空城)分享简介:海兰,在我MainWindow.xaml.cs文件我做了一个getter来获取引用我的列表框。In my MainWindow.xaml.cs file I made a getter to get the reference to my listbox.public ListBox LoggerList{ge...

海兰,

在我MainWindow.xaml.cs文件我做了一个getter来获取引用我的列表框。

In my MainWindow.xaml.cs file I made a getter to get the reference to my listbox.

public ListBox LoggerList
{
    get { return Logger; }
}    

现在我想从一个普通的类访问LoggerList,但我不工作。我试过如下:

Now I want to access the LoggerList from a normal class but I don't work. I tried the following:

MainWindow parentWindow = Window.GetWindow(this) as MainWindow;
object selectedItem = parentWindow.LoggerList;

但在* xaml.cs文件,而不是在一个正常的* cs文件这仅适用。

But this only works in a *xaml.cs file and not in a normal *.cs file.

最好的问候

推荐答案

有一些在WPF访问窗口取值方法。如果您有多个打开的,那么你可以通过它们循环是这样的:

There are a number of ways of accessing Windows in WPF. If you have several open, then you can iterate through them like this:

foreach (Window window in Application.Current.Windows) window.Close();

如果你有一个特定类型的自定义的窗口,你可以这样做:

If you had a particular type of custom Window, you could use this:

foreach (Window window in Application.Current.Windows.OfType<YourCustomWindow>()) 
    ((YourCustomWindow)window).DoSomething();

如果你只是经过参考主窗口,那么你可以简单地使用这样的:

If you are just after a reference to the MainWindow, then you can simply use this:

Window mainWindow = Application.Current.MainWindow;

但是,使用这种方法,有机会的话,它会返回。在这种情况下,请确保您设置的主窗口来这个属性在它的构造函数:

However, using this method, there is a chance that it will return null. In this case, make sure that you set the MainWindow to this property in it's constructor:

// From inside MainWindow.xaml.cs
Application.Current.MainWindow = this;

应当注意然而,@woutervs是正确的...你应该的没有的是从窗口访问UI控件 S在库类。你真的应该绑定数据收集到 ListBox.ItemsSource ,然后控制数据收集代替。

It should be noted however, that @woutervs is correct... you should not be accessing UI controls from Windows in library classes. You really should data bind collections to the ListBox.ItemsSource and then manipulate the data collection instead.

更新>>

我不知道为什么你的 Application.Current 对象 ...这可能是因为您'已经加载了类库到不同的的AppDomain 。无论哪种方式,我认为你是因小失大。实在没有理由类库类应该需要引用主窗口

I don't know why your Application.Current object is null... it could be because you've loaded your class library into a different AppDomain. Either way, I think that you are missing the big picture. There really is no reason why a class library class should need a reference to the main Window.

如果您需要在数据收集完成一些工作,然后只是通过从code中的数据收集的背后,或者你的视图模型。一旦工作完成,然后就传回的是数据绑定到的ItemsSource 属性。

If you need to perform some work on the data collection, then just pass the data collection from code behind, or your view model. Once the work is complete, then just pass it back to the UI where you have access to the ListBox and/or the collection that is data bound to the ItemsSource property.

阅读全文

相关推荐

最新文章