[英]Call public function in Main Window from a User Control WPF
我有一個主窗口,其中包含一些在 WPF XAML 中初始化的用戶控件
主窗口.xaml 。
<Grid>
<local:RegularUnit x:Name="ucRegularUnit" Grid.Row="0" />
<local:Actions x:Name="ucActions" Grid.Row="1" />
// .....
</Grid>
我在主窗口中有一個公共函數,我想在單擊用戶控件中的按鈕后調用它。 在搜索了一些解決方案后,我找到了一種在我的用戶控件類中獲取父窗口實例的方法,但是當我使用parentWindow.myFunction()
時它找不到該函數。
用戶控制RegularUnit.cs
:
public partial class RegularUnit : UserControl
{
public RegularUnit()
{
InitializeComponent();
}
private void Button_SearchSerialNumber_Click(object sender, RoutedEventArgs e)
{
Window parentWindow = Window.GetWindow(this);
//parentWindow. //Can't find the function myFunction()
}
}
MainWindow.cs
:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public void myFunction()
{
// Do Some Stuff...
}
}
我做錯了什么,我該如何解決?
您不能在parentWindow
上調用myFunction
,因為它不是標准 WPF Window
類的成員,而是您的自定義MainWindow
。
您可以做的是將Window.GetWindow(this)
的結果Window.GetWindow(this)
為MainWindow
,例如
MainWindow parentWindow = (MainWindow) Window.GetWindow(this);
parentWindow.myFunction();
然而,這是一個非常糟糕的類設計,因為現在您的用戶控件取決於嵌入到特定窗口中。
您應該做的是向父控件可以訂閱的用戶控件添加一個事件。
public event EventHandler SerialNumberSearch;
private void Button_SearchSerialNumber_Click(object sender, RoutedEventArgs e)
{
var handler = SerialNumberSearch;
if (handler != null) handler(this, EventArgs.Empty);
}
當然,您可以使用不同類型的 EventHandler,具體取決於您的需要。
System.Windows.Application.Current.Windows.OfType<YourWindow>().SingleOrDefault(x => x.IsActive).YourPublicMethod();
雖然上面的代碼是一種凌亂的方式,但它仍然完成了工作。
Dirk 建議的基於事件訂閱的解決方案。 我的事件基於一個簡單的委托,但您可以遵循類似的模式並將其基於適合您場景的委托。
// In UserControl
namespace TextEditor
{
public partial class TextEditorToolBar : UserControl
{
// you can use Action type delegate also
public delegate void getDocumentKeywords();
public event getDocumentKeywords getDocumentRakeKeywordsEvent;
public TextEditorToolBar()
{
InitializeComponent();
}
// This is event handloer for the button on your user control
private void ExtractRakeKeywords(object sender, RoutedEventArgs e)
{
var handler = getDocumentRakeKeywordsEvent;
if (getDocumentRakeKeywordsEvent != null)
getDocumentRakeKeywordsEvent();
}
}
}
// In MainWindow
namespace TextEditor
{
public partial class MainWindow : Window
{
private DocumentKeywordsExtractor KeyWordsExtractor;
public MainWindow()
{
InitializeComponent();
KeyWordsExtractor = new DocumentKeywordsExtractor(richTextBox);
// toolbar is the name given to UserControl in MainWindow.xaml
toolbar.getDocumentRakeKeywordsEvent += ExtractRakeKeywords;
}
private void ExtractRakeKeywords()
{
KeyWordsExtractor.GetRakeKeywords();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.