将值赋给Window1中ViewModel的TextBlock.Text,并将该值用于Window2



MVVM和WPF应用程序遇到一个特殊问题。我将对此作简要解释,以使其尽可能清楚。

首先,我在XAML文件中绑定了TextBlock属性的文本

XAML

<TextBlock
x:Name="ProjectCredentials"
Text="{Binding Path=HeaderName}"/>

视图模型-在主窗口中创建

namespace Test
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public class MainWindowViewModel : INotifyPropertyChanged
{
private string _tabitemHeader;
public string HeaderName
{
get
{   
return _tabitemHeader;
}
set
{
_tabitemHeader = value;
OnPropertyChanged("HeaderName");
}
}
}
// Continue in next code block
}

下面是登录屏幕窗口或窗口1,我想从中为TextBlock.Text属性赋值。

namespace Test
{
public partial class LoginScreen : Window
{
public LoginScreen()
{
InitializeComponent();
}
private void LoginButton_Click(object sender, RoutedEventArgs e)
{
MainWindow win2 = new MainWindow();
win2.DataContext = new MainWindow.MainWindowViewModel();
MainWindow.MainWindowViewModel object_change = win2.DataContext as MainWindow.MainWindowViewModel;
object_change.HeaderName = "Project Name: " + SQLSeverName.Text + " - " + SQLDatabasesComboBox.SelectedItem;
Debug.WriteLine(object_change.HeaderName);
//Successfully returns the string
}
}
}

既然我已经给出了值"Project Name: ...",我应该在方法GetHeaderDetails()内的MainWindow中调用这个字符串

namespace Test
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public class MainWindowViewModel : INotifyPropertyChanged
{
private string _tabitemHeader;
public string HeaderName
{
get
{   
return _tabitemHeader;
}
set
{
_tabitemHeader = value;
OnPropertyChanged("HeaderName");
}
}
}
public List<string> GetHeaderDetails()
{
string projectdetails_option1 = ?.HeaderName; //how can  I call the HeaderName of MainWindow DataContext which is already filled from LoginScreen window?
Debug.Assert(projectdetails_option1 != null, "Project name not found!"); //this returns null
string connectiondetails = projectdetails_option1.Split(": ")[1];
string servernamedetails = connectiondetails.Split(" - ")[0].Trim();
string projectnamedetails = connectiondetails.Split(" - ")[1].Trim();
List<string> connectiondetailslist = new List<string>();
connectiondetailslist.Add(servernamedetails);
connectiondetailslist.Add(projectnamedetails);
return connectiondetailslist;
}
public List<string> ConnectionDetailsList { get => GetHeaderDetails(); set => ConnectionDetailsList = value; }
}

这里的问题是如何调用已经从LoginScreen窗口填充的MainWindow DataContext的HeaderName?

我知道,如果我在GetHeaderDetails((方法中打开MainWindow DataContext的一个新实例,我将得到一个NullReferenceException,因为HeaderName将丢失,并且将引入一个新的DataContext。所以我想找到一种绕过这个的方法

请注意,我知道NullReferenceException。尽管如此,我正在寻找可能帮助我理解如何定位问题的答案

谨致问候。

我终于想通了。要在MainWindow中检索TextBlock.Text值,我唯一需要做的就是:

而不是:

string projectdetails_option1 = ?.HeaderName;

我试过这个:

string projectdetails_option1 = ProjectCredentials.Text; //The TextBlock that got its value from LoginScreen.

我成功地检索了ProjectCredentials文本块的值,而没有打开DataContext的新实例。

最新更新