我确信我已经搜索了很多并尝试了很多方法来解决它。但是我做不到。
我有这样的用户控件:
public partial class Categories : UserControl
{
public Categories()
{
InitializeComponent();
}
public void GetCats()
{
string sqlcmdString = "select * from categories";
string connString = @"Data Source=DESKTOP-L6OBVA4\SQLEXPRESS;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],这意味着:类别的选项卡。获取新数据。感谢。
答案 0 :(得分:1)
您可以转换当前所选Content
的{{1}}属性:
TabItem