2017-04-13 1 views
1

나는 많은 부분을 검색하고이를 해결하기 위해 많은 노력을 기울였습니다. 그러나 나는 그것을 할 수 없었다. 기본 창에서 사용자 컨트롤의tabcontrol에서 탭을 변경할 때 다른 창에서 TabItem의 데이터를 다시로드하십시오. WPF

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() 메소드 :

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(); 
    } 
} 

메인 창

는이 같은 사용자가 제어 할 수 있습니다? TabItem [1]을 업데이트하는 방법, 즉 탭의 범주를 의미합니다. 새로운 데이터를 얻을 수 있습니다. 감사.

답변

0

당신은 현재 TabItem 선택의 Content 속성을 캐스팅 수 :

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

아를! 그것은 잘 작동합니다. 고마워요. 너는 내 하루를 보냈다. –

관련 문제