ContentControl を使用することが提案されたこの質問のフォローアップとして、ページで ContentControl から派生したカスタム メイド クラスを使用すると、その ContentControl 内で定義されたコントロールにページからアクセスできないというシナリオに遭遇しました。すべてのメンバー変数は null になります。
たとえば、ContentControlから派生して作成したカスタム クラスの名前がMyGroupBoxで、これを Page コントロール内で使用しようとするとします。
<UserControl x:Class="MyApplication.MyUserControl">
<local:MyGroupBox Title="Basic Information">
<TextBox x:Name="MyTextBox" />
</local:MyGroupBox>
</UserControl>
ページの分離コード内から MyTextBox にアクセスしようとすると、メンバー変数が null になります。このシナリオでこれらのコントロールにアクセスして、ページのコード ビハインドで使用できるようにするための最善の回避策は何ですか?
ありがとう!
編集: MyGroupBox コントロールの既定のテンプレートは次のとおりです。
<Style TargetType="local:MyGroupBox">
<Setter Property="Foreground" Value="#FF000000"/>
<Setter Property="HorizontalContentAlignment" Value="Left"/>
<Setter Property="VerticalContentAlignment" Value="Top"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:MyGroupBox">
<Border BorderThickness="1" Margin="8,8,0,0">
<Border.BorderBrush>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FF979797" Offset="0"/>
<GradientStop Color="#FFF1F1F1" Offset="1"/>
</LinearGradientBrush>
</Border.BorderBrush>
<StackPanel>
<Grid>
<Rectangle>
<Rectangle.Fill>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="White" Offset="0"/>
<GradientStop Color="#FFDFE2ED" Offset="1"/>
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>
<TextBlock Text="{TemplateBinding Title}" Margin="10,3,3,3" TextAlignment="Center" HorizontalAlignment="Left" />
</Grid>
<ContentPresenter Cursor="{TemplateBinding Cursor}" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
</StackPanel>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
編集:
public MyUserControl()
{
InitializeComponent();
if (this.MyTextBox == null)
{
// MyTextBox is null at this point - is there a way to get
// the InitializeComponent method to find the control named MyTextBox when
// it is inside of a ContentControl derived class?
MessageBox.Show("MyTextBox is null");
}
}