如何在WPF开发中调用其他窗口内textbox控件的字符串内容
跨WPF窗口获取其他窗口TextBox控件文本的可行解决方案
- 通过公共属性暴露内容(入门场景最推荐)
不要直接公开控件,在目标窗口后台代码封装只读公共属性绑定TextBox文本即可,符合封装原则。
目标窗口(示例名称为TargetWindow)XAML代码:
<TextBox x:Name="UserInputTextBox" Text="待获取的文本内容"/>
目标窗口后台代码:
public partial class TargetWindow : Window { // 公共只读属性暴露TextBox内容 public string UserInputContent => UserInputTextBox.Text; public TargetWindow() { InitializeComponent(); } }
调用窗口获取内容的代码:
// 保留你打开目标窗口时的实例 TargetWindow targetWin = new TargetWindow(); targetWin.Show(); // 任意需要获取内容的时机调用属性 string result = targetWin.UserInputContent;
- 通过事件回调实时传递内容
适合需要在TextBox内容变更时实时获取、不需要主动轮询的场景。
目标窗口后台代码:
// 定义文本变更事件 public event Action<string> InputTextUpdated; private void UserInputTextBox_TextChanged(object sender, TextChangedEventArgs e) { // 文本变更时触发事件传递最新内容 InputTextUpdated?.Invoke(UserInputTextBox.Text); }
调用窗口注册事件即可实时接收内容:
TargetWindow targetWin = new TargetWindow(); targetWin.InputTextUpdated += newText => { // 此处直接获取实时更新的文本 Console.WriteLine(newText); }; targetWin.Show();
- MVVM架构下共享ViewModel(生产项目最推荐)
如果项目采用MVVM架构,不需要窗口之间直接交互,将两个窗口的DataContext绑定到同一个ViewModel实例的对应字符串属性即可。
示例共享ViewModel代码:
public class SharedInputViewModel : INotifyPropertyChanged { private string _inputText; public string InputText { get => _inputText; set { _inputText = value; OnPropertyChanged(); } } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } }
两个窗口的TextBox都绑定InputText属性,任意窗口都可以直接从ViewModel实例读取最新的文本内容。
注意:不建议直接将目标窗口TextBox的
x:FieldModifier设置为public直接访问控件,该方式会产生强耦合,违反封装原则,后续维护成本极高。
内容的提问来源于stack exchange,提问作者Sarper Eroglu
相关产品推荐
相关产品推荐

