【问题标题】:How do I call a method in child User control when MainWindow Tab is changed更改 MainWindow 选项卡时如何在子用户控件中调用方法
【发布时间】:2015-04-14 09:20:06
【问题描述】:

如何从 MainWindow 调用 UC 中的方法?在我的应用程序中,我使用 MainWindow + UserControls + TabControl(一个用户控件 = 一个 tabitem,作为 firefox)。当我更改 tabitem 时,我会在用户控件中调用方法。我会用一个例子来解释这一点。

用户控制代码:

    MainWindow mw;
   public userControl(MainWindow main)
    {
        this.mw = main;
        InitializeComponent();
        LoadData();
    }

     public void LoadData()
    {
        using (var mod = new Data())
        {
            try
            {
                var query = (from c in mod.table
                             select c).ToList();
                dataGrid.ItemsSource = null;
                dataGrid.ItemsSource = query;             
            }
            catch {}
        }
    }

主窗口代码:

    public void RefreshUserControl(string userControlName)
    {
        switch (userControlName)
        {//... others UC
          // ....
            case "userControl":
             userControl ue = new userControl(this);
             ue.LoadData();
                break;
        }
    }

    private void tabUC_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var item = sender as TabControl;
        var selected = item.SelectedItem as TabItem;
        if (selected != null)
        {
            RefreshUserControl(selected.Name.ToString());              
        }
    }

通常,示例 - 当我更改“userControl”上的 tabitem 时,然后刷新此 usercontrol 上的数据网格。请帮忙

【问题讨论】:

    标签: c# wpf user-controls


    【解决方案1】:

    虽然我建议你改变你在这里创建 UC 的方法,以便在 UC 中不依赖 MainWindow,但如果你现在想继续使用它,

    • 您可以在主窗口中进行活动
    • 选项卡选择更改时引发该事件
    • 在 UC 中收听该事件,因为您有 MainWindow 参考
    • 在 UC 的事件处理程序中做任何你想做的事情

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-22
      • 2018-07-01
      • 2017-10-20
      • 2011-09-30
      • 2023-01-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多