如何在wpf中保持隐藏窗口在后台运行?

时间:2014-01-14 10:32:04

标签: c# wpf

如果隐藏窗口,我怎么能保持窗口活着,我正在尝试使用此代码..

Win1:包含当前时间和日期。 ON按钮单击win2窗口打开,win1 Hides。

Win2:在win2窗口中,我使用了属性传递了win1文本框的值。

但是在win2中,时间没有得到更新..这意味着win1不再活着

有什么建议吗?

{
    public win1()
    {
        InitializeComponent();

        DispatcherTimer timer = new DispatcherTimer(new TimeSpan(0,0,1), DispatcherPriority.Normal, delegate
        {
            this.textb.Text = DateTime.Now.ToString("HH:mm:ss tt");
        }, this.Dispatcher);
    }

    private void Grid_Loaded(object sender, RoutedEventArgs e)
    {

    }

    private void but_send_Click(object sender, RoutedEventArgs e)
    {
        win2 w2 = new win2();
        w2.passval = textb.Text;
        this.Hide();
        w2.ShowDialog();
    }
}

这是我的第二个窗口win2.xaml.cs

{
    private string nm;

    public string passval
    {
        get { return nm; }
        set { nm = value;}
    }     

    public win2()
    {
        InitializeComponent();

    }

    private void Grid_Loaded(object sender, RoutedEventArgs e)
    {
        lbl1.Content = "Time " + nm;
    }    
}

1 个答案:

答案 0 :(得分:0)

问题是你正在更新Win1的TextBox。以下行将textb.Text中的字符串复制到w2.passval

w2.passval = textb.Text;

但就是这样:textb.Text的进一步更新对w2.passval属性没有影响。

此外,在w2中保留对Win1的引用并直接从您的委托中更新w2.passval,也不会更新lbl1的内容,因为您只在网格时更新其值已加载。因此,您需要:

  1. w2.passval中的委托更新Win1。例如:

    public win1()         
    {
        InitializeComponent();
    
        DispatcherTimer timer = new DispatcherTimer(new TimeSpan(0,0,1), DispatcherPriority.Normal, delegate
        {
            this.textb.Text = DateTime.Now.ToString("HH:mm:ss tt");
            if (_w2 != null)
                _w2.passval = textb.Text;
        }, this.Dispatcher);
    }
    
    private win2 _w2 = null; // Reference to your Win2
    
    private void but_send_Click(object sender, RoutedEventArgs e)
    {
        _w2 = new win2();
        _w2.passval = textb.Text;
        this.Hide();
        w2.ShowDialog();
    }
    
  2. 更新Label中的Win2。例如:

    private string nm;
    
    public string passval
    {
        get { return nm; }
        set { 
            nm = value; 
            // This should rather be done somewhere else, not in the setter
            lbl1.Content = "Time " + nm; 
        }
    }