You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# WPF实现两窗口间变量变更或按钮点击时的数据传递

解决WPF两个窗口间数据传递并更新TextBox的问题

嘿,我来帮你搞定这个WPF窗口间数据传递的需求!首先回答你的问题:如果想用更优雅的数据绑定方式,需要提供Window1中Tb_kunden_id的XAML代码;如果用代码后台更新,没有XAML也能实现,但绑定会更符合WPF的设计思想。下面给你两种可行的解决方案,同时帮你优化现有代码的潜在问题。

方案一:用静态类+事件通知(适合简单场景)

你的静态类Informationen_bestellungen可以扩展事件机制,当kunden_id变更时主动通知Window1更新TextBox。这样既满足按钮点击触发,也能响应数据变更。

1. 修改静态类,添加事件通知

public static class Informationen_bestellungen
{
    private static string _kundenId;
    // 用属性封装,变更时触发事件
    public static string KundenId
    {
        get => _kundenId;
        set
        {
            if (_kundenId != value)
            {
                _kundenId = value;
                KundenIdChanged?.Invoke(null, EventArgs.Empty);
            }
        }
    }

    // 定义事件,供Window1订阅
    public static event EventHandler KundenIdChanged;
}

2. 在Window1中订阅事件并更新TextBox

在bestellung_hinzufügen窗口的构造函数里订阅事件,记得窗口关闭时取消订阅避免内存泄漏:

public partial class bestellung_hinzufügen : Window 
{ 
    string login = Login_info.login; 
    string datum = ""; 
    int m_id_auslesen = 0; 

    public bestellung_hinzufügen() 
    { 
        InitializeComponent(); 
        // 订阅数据变更事件
        Informationen_bestellungen.KundenIdChanged += OnKundenIdChanged;
        
        // 原有的数据库连接代码...
        NpgsqlConnection connection = new NpgsqlConnection(login); 
        try { connection.Open(); } 
        catch { MessageBox.Show("failed"); } 
    } 

    // 数据变更时更新TextBox(注意UI线程安全)
    private void OnKundenIdChanged(object sender, EventArgs e)
    {
        Dispatcher.Invoke(() => 
        {
            Tb_kunden_id.Text = Informationen_bestellungen.KundenId;
        });
    }

    // 窗口关闭时取消订阅
    protected override void OnClosed(EventArgs e)
    {
        base.OnClosed(e);
        Informationen_bestellungen.KundenIdChanged -= OnKundenIdChanged;
    }

    // 原有的按钮点击方法...
    private void Btn_kunde_suchen_Click(object sender, RoutedEventArgs e) 
    { 
        Auswahl_kunde_bestellung auswahl_Kunde_Bestellung = new Auswahl_kunde_bestellung(); 
        auswahl_Kunde_Bestellung.Show(); 
    } 

    private void Btn_abbrechen_Click(object sender, RoutedEventArgs e) 
    { 
        this.Close(); 
    } 
}

3. 修改Window2的按钮点击逻辑

直接设置静态属性,自动触发事件:

private void Btn_kunde_hinzufügen_Click(object sender, RoutedEventArgs e) 
{ 
    if (Liste_ausgabe_kunden.SelectedIndex != -1) 
    { 
        string selectedItem = Liste_ausgabe_kunden.SelectedItem.ToString(); 
        string[] splitItems = selectedItem.Split(); 
        // 设置属性,自动触发事件通知Window1
        Informationen_bestellungen.KundenId = splitItems[0]; 
        this.Close(); 
    } 
}

方案二:用数据绑定(WPF推荐方式)

如果想让TextBox自动更新,不需要手动写事件处理,可以用数据绑定结合INotifyPropertyChanged。我们改成单例类来实现:

1. 创建可绑定的数据类

public class Informationen_bestellungen : INotifyPropertyChanged
{
    // 单例实例
    private static readonly Informationen_bestellungen _instance = new Informationen_bestellungen();
    public static Informationen_bestellungen Instance => _instance;

    private string _kundenId;
    public string KundenId
    {
        get => _kundenId;
        set
        {
            if (_kundenId != value)
            {
                _kundenId = value;
                OnPropertyChanged(nameof(KundenId));
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

2. 在Window1的XAML中绑定TextBox

假设你的命名空间是YourNamespace,先添加命名空间引用,再绑定:

<Window x:Class="YourNamespace.bestellung_hinzufügen"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:YourNamespace"
        Title="Bestellung Hinzufügen" Height="450" Width="800">
    <Grid>
        <!-- 绑定到单例类的KundenId属性 -->
        <TextBox x:Name="Tb_kunden_id" Text="{Binding Source={x:Static local:Informationen_bestellungen.Instance}, Path=KundenId, Mode=OneWay}" />
        <!-- 其他控件... -->
    </Grid>
</Window>

3. Window2的按钮点击逻辑不变,设置单例属性即可

Informationen_bestellungen.Instance.KundenId = splitItems[0];

重要优化:避免SQL注入风险

你的现有SQL代码直接拼接用户输入,存在严重的SQL注入漏洞!一定要改成参数化查询,比如:

// 替换Btn_suchen_Click中的SQL代码
if (Combo_auswahl_kunde.SelectedIndex == 0)
{
    using (NpgsqlCommand cmd = new NpgsqlCommand("select * from tbl_kunde where k_id >= @suchanfrage order by k_id;", connection))
    {
        cmd.Parameters.AddWithValue("@suchanfrage", suchanfrage);
        // 执行查询并绑定到列表...
        Ausgabe_kunde(cmd);
    }
}

这样不管用户输入什么,都不会破坏SQL结构,安全性大大提升。

内容的提问来源于stack exchange,提问作者hello_there_I_need_help

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:35:53