【问题标题】:Unable to set a TextBox text owned by MainWindow from another class无法从另一个类设置 MainWindow 拥有的 TextBox 文本
【发布时间】:2018-08-18 22:57:31
【问题描述】:

我正在尝试从同一命名空间中的另一个类设置 MainWindow(WPF 窗口)拥有的 TextBox 值文本,但没有任何反应。我已经对类似问题提出了许多建议和答案,但无济于事。令我困惑的是,MainWindow 的 SetText 在 Visual Studio 控制台中显示文本时接收文本,但对实际文本框没有任何影响。 “ConsoleLog”文本框具有默认 XAML 值。

所以我的 MainWindow 是这样的:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }    

    public string SetText
    {
        get { return ConsoleLog.Text; }
        set {
            Console.WriteLine(value);
            ConsoleLog.Text = value;
        }
    }
}

在我的 App 类中:

public partial class App : Application
{
    private void Test()
    {
        var mw = new MainWindow();
        mw.SetText = "Please display something!";
    }
}

我尝试了其他几种方法,例如:

((MainWindow)System.Windows.Application.Current.MainWindow).ConsoleLog.Text = "Please display something!";

但到目前为止,没有任何错误消息。

我对 WPF C# 还很陌生,我确信这是我很明显缺少的东西,但这让我抓狂。

【问题讨论】:

    标签: c# .net wpf c#-4.0


    【解决方案1】:

    WPF 项目 默认项目通过配置其 App.xaml 文件而不是 app.xml.cs 来启动 MainWindow。如果您想访问 MainWindow ,您应该通过以下代码手动启动 MainWindow

    public App()
    {
        var mw = new MainWindow();
        mw.SetText = "Please display something!";
        mw.ShowDialog();
    }
    

    并从 App.xaml 中删除以下行

    StartupUri="MainWindow.xaml"
    

    如果你想开始使用 WPF 应用程序并制作一个好的应用程序,我建议你看一些基础教程,并尝试学习 MVVM(或 Web 中的 MVC)编程方法。

    【讨论】:

    • 啊,谢谢!那成功了。我错过了 App.xaml 中的 StartupUri 部分。为了参考其他人,我不得不在我的代码的某些部分使用this.Dispatcher.Invoke(() => { mw.SetText = "Test"; });以避免调用线程错误。
    • 如果您使用 MVVM 方法,您将减少从其他线程调用的使用。我忘了线程干扰。我的错。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-10
    • 1970-01-01
    • 2013-03-05
    • 2012-04-27
    • 2019-05-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多