无法在父窗口中获取子窗口变量值

时间:2013-11-30 09:22:34

标签: c# wpf

描述 - 我的主窗口有状态标签,以连接和断开的形式显示状态。当我在子窗口中创建一个对象(父窗口)并设置标签状态时,它不会反映在父窗口中。 。我也试过,拿了一个布尔变量并在子窗口代码中设置为值1,但是当我在父窗口中访问该变量时,默认值为零。

/// My parent window code

public partial class MainWindow : Window
{  
    public CompSetting obj = new CompSetting();
    public MainWindow()
    {   
       InitializeComponent();
    }

    private void click(object sender, MouseButtonEventArgs e)
    {
        CompSetting compPortseting = new CompSetting();
        compPortseting.ShowDialog();
    }

    private void button_Click(object sender, RoutedEventArgs e)
    {
        if (obj.flag  == 1) // Here i get by defult value 0 . but already set to 1 on child window. In short cant access flag variable value.
        {
            LblPortStatus_lable.Content = "chetas";
        }
        else
        {
            LblPortStatus_lable.Content = "rahul";
        }
    }
}

// My child window code 
public partial class CompSetting : Window
{ 
    public  int flag  ;
    public CompSetting()
    {
        InitializeComponent();
    }

    private void button_Click(object sender, RoutedEventArgs e)
    {
        flag = 1;
    }
}

1 个答案:

答案 0 :(得分:0)

private void click(object sender, MouseButtonEventArgs e)
{
    if(obj != null)
    {
        obj.ShowDialog();
    }
}

不要创建新对象,只需使用现有对象。

<强>附加

考虑创建设置对象的实例,而不是创建子窗口的实例。然后,子窗口将获得对设置对象的引用并对其进行修改:

public partial class MainWindow : Window
{  
    public CompSetting settings = new CompSetting();
    public MainWindow()
    {   
        InitializeComponent();
    }

    private void click(object sender, MouseButtonEventArgs e)
    {
        var settingsDialog = new SettingDialog(settings);
        settingsDialog.ShowDialog();
    }

    private void button_Click(object sender, RoutedEventArgs e)
    {
        if (settings.Flag  == 1) 
        {
            LblPortStatus_lable.Content = "chetas";
        }
        else
        {
            LblPortStatus_lable.Content = "rahul";
        }
    }
}

// My child window code 
public partial class SettingDialog : Window
{ 
    private CompSettings settings

    public SettingsDialog(CompSettings settings)
    {
        this.settings = settings;
    }

    private void button_Click(object sender, RoutedEventArgs e)
    {
        this.settings.Flag = 1;
    }
}

public class CompSettings
{
    public int Flag;
}
相关问题