更改选项卡控件 WPF 上的选项卡时,从另一个窗口重新加载 TabItem 中的数据



我相信我已经搜索了很多,并尝试了很多方法来解决它。 但我做不到。

我有一个这样的用户控件:

public partial class Categories : UserControl
{
    public Categories()
    {
        InitializeComponent();
    }
    public void GetCats()
    {
        string sqlcmdString = "select * from categories";
        string connString = @"Data Source=DESKTOP-L6OBVA4SQLEXPRESS;Initial Catalog=QLDB;Integrated Security=True";
        SqlConnection con = new SqlConnection(connString);
        SqlCommand cmd = new SqlCommand(sqlcmdString, con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        con.Open();
        DataTable dt = new DataTable();
        da.Fill(dt);
        dgv_categories.ItemsSource = dt.AsDataView();
    }
}

和主窗口:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }
    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        var tabs = new ObservableCollection<TabItem>  {
            new TabItem() { Content = new Import(), Header = "Import from Excel files"},
            new TabItem() { Content = new Categories(), Header = "Categories" },
            new TabItem() { Content = new Products(), Header = "Products"}
        };
        tabControl.ItemsSource = tabs;
    }

    private void tabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (e.OriginalSource == this.tabControl)
        {
            if (this.tabControl.SelectedIndex == 1)
            {
               // personally, i need to do something here to call GetCats() method to reload all all categories from database to datagridview
            }
        }
    }
}

如何从主窗口调用用户控件中的 GetCats(( 方法? 或者换句话说,如何更新 TabItem[1],这意味着:类别选项卡。 以获取新数据。谢谢。

您可以强制转换当前选定TabItemContent 属性:

private void tabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (e.OriginalSource == this.tabControl)
    {
        if (this.tabControl.SelectedIndex == 1)
        {
            TabItem ti = tabControl.SelectedItem as TabItem;
            Categories c = ti.Content as Categories;
            if (c != null)
            {
                c.GetCats();
            }
        }
    }
}

最新更新