我正在使用带有MVVM原则的WPF。视图如下所示:
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="MyResources.xaml" />
</ResourceDictionary.MergedDictionaries>
<DataTemplate x:Key="ValveOptionTemplate" >
<Grid Margin="{StaticResource MyApp.DefaultMarginTopBottomThin}"
VerticalAlignment="Center">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<myApp:CheckBox Grid.Column="0" Grid.Row="0"
Margin="{StaticResource
MyApp.DefaultMarginTopBottomThin}"
IsChecked="{Binding IsSelected}"
VerticalAlignment="Center"
Checked="ToggleButton_OnChecked"/>
<myApp:TextBox Grid.Column="1" Grid.Row="0"
Width="300"
Margin="{StaticResource MyApp.DefaultMarginLeftThin}"
VerticalAlignment="Center"
Text="{Binding Description,
UpdateSourceTrigger=PropertyChanged}"
IsEnabled="{Binding IsEditable}"
x:Name="textBox"/>
</Grid>
</DataTemplate>
</ResourceDictionary>
</UserControl.Resources>
<Grid x:Name="OptionGrid">
<ItemsControl x:Name="Options" ItemsSource="{Binding Options}"
ItemTemplate="{StaticResource ValveOptionTemplate}"
FocusVisualStyle="{x:Null}"
Margin="{StaticResource MyApp.DefaultMarginTopBottomThin}"/>
</Grid>我想说没什么奇怪的。我正在尝试访问myApp:TextBox以将焦点设置在它上面。为此,我在后台代码中使用了这个(未完成的)代码片段(我知道什么是MVVM原则,并且我不认为我违反了它们)。
private void ToggleButton_OnChecked( object sender, RoutedEventArgs e )
{
var cp = Options.ItemContainerGenerator.ContainerFromIndex(0) as ContentPresenter;
var dt = cp.ContentTemplate; //<--this is null! Why?
var tb = (TextBox)(dt.FindName( "textBox", cp ));
}您在事件处理程序中看到我的注释了吗?contenttemplate是否为空?为什么?哪里出了问题?
发布于 2013-12-01 00:25:35
在计算绑定的时候,完整的可视化树还没有构建。
这就是模板不可用的原因。
为了解决这个问题,你必须使用Dispatcher.BeginInvoke()在UI线程的后台调用cp.ApplyTemplate或者推迟代码的执行。
https://stackoverflow.com/questions/20301786
复制相似问题