2017-04-13 7 views
1

私は多くの方法で検索し、解決することを試みたと確信しています。私はそれをすることができませんでした。tabcontrolのタブを変更するときに別のウィンドウからTabItemのデータをリロードするWPF

私はこのようなユーザーコントロールを持っている:

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

あなたは、現在選択されて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(); 
      } 
     } 
    } 
} 
+0

AWを!それはうまく動作します。どうもありがとうございました。あなたは私の一日を作った。 –

関連する問題