gpt4 book ai didi

c# - 在 C#/WPF 中打开新窗口并向其传递参数的语法

转载 作者:行者123 更新时间:2023-12-05 06:45:18 24 4
gpt4 key购买 nike

在我的 C#/WPF 应用程序中,用户可以单击一个按钮来创建一个新窗口来显示一些图形。目前按钮处理程序中的代码如下所示。 . .

var window = (Window)System.Windows.Application.LoadComponent(new Uri("ShowGraphics.xaml", UriKind.Relative));
window.Owner = this; // keeps the Window on top of the parent window
window.Title = "Show Graphics";
window.Left = 700;
window.Top = 500;
window.Show();

现在我想使用构造函数语法将一个参数传递给新窗口的构造函数,就像这样(伪代码......)

  Window myWindow = new Window("ParameterValue");
myWindow.Show();

...但我不知道使用关联的 XAML 文件和其他属性声明窗口并传递要在新窗口的构造函数中读取的参数的正确语法是什么。

PS - 当我们讨论这个主题时,我如何将值返回到按钮所在的主窗口?

第一部分的答案我认为这就是 Roman Ko 在写作时试图达到的目的

"public partial class TestDialog : Window"

但我需要做的不是从 .Net Window 类派生它,而是从我特定的向导创建的类派生它(在 VS2010 中添加 > 新项目...)。因为 Visual Studio 会同时创建 .cs 文件和 .xaml 文件,所以窗口通过这种方式与其 XAML 布局相关联。然后传递参数,只需通过构造函数即可。从而调用它。 . .

    var window = new TheNameSpace.ShowGraphics("parameter"); 
window.Owner = this; // keeps the Window on top of the parent window
window.Title = "Show Graphics";
window.Left = 700;
window.Top = 500;
window.Show();

...并在构造函数中使用它。 . .

public ShowGraphics(String sParam)
{
InitializeComponent();
// do stuff
}

PS 的答案一种方法是覆盖子窗口的方法,例如,show()

// Override Show()
public void Show (out string sResult)
{
Show(); // call the base class method
sResult = "foo";
return;
}

...然后,在调用者...

string sReturnVal;
window.Show(out sReturnVal);

最佳答案

尝试这样的事情(如果你不想遵循 MVVM 模式):

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

private void Button_Click(object sender, RoutedEventArgs e) {
string inputParam = "some value";
string outputValue;
TestDialog dlg = new TestDialog(inputParam);
if (dlg.ShowDialog() == true)
outputValue = dlg.OutputParam;
}
}

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

public TestDialog(string inputParam) {
InitializeComponent();
OutputParam = inputParam.ToUpper(); // for example
}

public string OutputParam { get; private set; }

private void btnOK_Click(object sender, RoutedEventArgs e) {
DialogResult = true;
}

}

关于c# - 在 C#/WPF 中打开新窗口并向其传递参数的语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25164079/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com