Cant get a control from a TabControl DataTemplate

前端 未结 1 471
囚心锁ツ
囚心锁ツ 2021-01-18 14:58

I\'ve been googling this for the last 2 days and cant get anywhere, I just cant do anything to any control in a datatemplate of a tabcontrol.

First off, the code:

相关标签:
1条回答
  • 2021-01-18 15:43

    Looks like it's issue with the way the TabControl is being instantiated by the run time. It appears that the first time the SelectionChanged event is being raised the ContentTemplate is not quite ready to be accessed. If you run your code again and skip over the first access of ContentTemplate you'll see that in subsequent events you can access this property without the exception being thrown.

    Often these types of errors can be overcome by calling Dispatcher.BeginInvoke, in this case it allows the run time to finish initializing the tab control before executing your code.

    Dispatcher.BeginInvoke(new Action(() =>
        {
            ContentPresenter cp = tabControl1.Template.FindName("PART_SelectedContentHost", tabControl1) as ContentPresenter;
            Grid g = tabControl1.ContentTemplate.FindName("myGrid", cp) as Grid;
            g.Background = new SolidColorBrush(Colors.Red);
        }));
    
    0 讨论(0)
提交回复
热议问题