我正在使用带有 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 ));
}
您在事件处理程序中看到我的评论了吗?内容模板为空?为什么?做错了什么?