我试图从相同名称空间中的另一个类设置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#还是很陌生,我敢肯定我很想念它,但这让我发疯了。
答案 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)编程方法。