[英]How to get result from custom WPF window to parent window in UserControl
[英]Get Text of Custom Dialog (UserControl) from Parent UserControl
我有一個UserControl作為Parent,並且正在打開一個自定義對話框(用戶控件),如以下代碼所示:
Window dialog = new Window
{
Title = "A Dialog Box",
Content = new UserControlDialog(),
SizeToContent = SizeToContent.WidthAndHeight,
ResizeMode = ResizeMode.NoResize
};
dialog.ShowDialog();
如何從UserControl對話框中的文本框中獲取文本?
首先,在您的UserControlDialog
控件中創建一個公共屬性,假設它名為Value
。 當用戶在對話框中執行某些操作時,請將TextBox
中的Value
設置為Value
屬性:
Value = SomeTextBox.Text;
關閉對話框窗口時,只需從dialog
控件中讀取值:
...
dialog.ShowDialog();
string result = dialog.Value;
更好的解決方案是將Value
屬性綁定到內部TextBox
控件,但是要實現此目的,您要么需要實現INotifyPropertyChanged
接口 ,要么將Value
屬性創建為DependencyProperty
:
在UserControlDialog
控件內:
<TextBox Text="{Binding Value, RelativeSource={RelativeSource
FindAncestor={x:Type YourLocalPrefix:UserControlDialog}}}" ... />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.