如何在加载到 UserControl 顶部的 window 中访问一个 UserControl 的代码隐藏数据?

How do I access one UserControl's code behind data in a window that is loaded on top the UserControl?

我有一个带有 UserControl 的 WPF 应用程序,我的大部分应用程序都在其中。在这个 UserControl 中,我有几个不同的控件来保存用户信息。保存数据时,我在 UserControl 上创建了一个 window "pops ups" 以确认保存。

在这个 Window 中,我需要将 UserControl 中的一些数据显示回用户并保存到数据库中。

我已经在 Window 中创建了一个 UserControl 对象,以便这样访问控件:

    UserControl Ctrl = new UserControl();

但是这个 UserControl 不再包含我需要的值。此外,UserControl 的构造函数采用可选参数。我发现在 XAML 中创建引用以访问控件会产生错误 "The type "UserControlName" does not include any accessible constructors."

我正在对应用程序执行代码隐藏方法,并希望在大多数情况下继续这样做。但是使用 dataBinding 不是问题。

我的问题是:Window 如何访问 UserControl 的控件或代码隐藏中保存的不同值,以便我可以将 UserControl 中的必要数据保存在 Window?

UserControl 的 XAML 部分是必需的:

<TextBox x:Name="txtUserName" Grid.Row="0" Grid.Column="1" Margin="0,0,0,20"/>
<TextBox x:Name="txtName" Grid.Row="1" Grid.Column="1" Margin="0,11,0,31" Height="30" VerticalAlignment="Center" TextChanged="txtName_Change"/>
<ComboBox x:Name="cboPasswordExpire" Grid.Row="2" Grid.Column="3" Margin="0,0,0,20" Height="30"/>
<TextBox x:Name="txtUserID" Grid.Row="2" Grid.Column="1" Margin="0,0,0,20" Height="30" TextChanged="txtUserID_Change"/>

Window 使用 DataTable 来保存值,此 DataTable (rowSecurityTrans) 用于写入数据库。需要如何从 Window 中的 UserControl 访问值的示例是这样的(我正在使用上面示例中使用无效对象的 'Ctrl'):

 rowSecurityTrans["Name"] = Ctrl.txtName.Text;
 rowSecurityTrans["UserID"] = Ctrl.txtUserID.Text;
 strUserName = userEditor.txtUserName.Text;
 rowSecurityTrans["PasswordDuration"] = General.PasswordConverter(Ctrl.cboPasswordExpire.SelectedIndex);

听起来您需要的是一个通用的 window,它将获取从任何来源提供的任何数据并显示出来。

你最好的办法是创建一个接口,每个其他 类 实现处理格式化和保存,并让 window 接受该接口类型的对象和调用这些方法来显示输出并保存数据

或者,另一方面,每个控件都必须实现一个接口来处理它们自己的 window 显示和数据保存。