作为建议我使用 ContentControl 的这个问题的后续行动,当我在页面上使用从 ContentControl 派生的自定义类时,我遇到了一个场景,该 ContentControl 中定义的任何控件都无法从页面访问。所有成员变量都为空。
例如,假设我创建的从ContentControl派生的自定义类名为MyGroupBox,我尝试在 Page 控件中使用它:
<UserControl x:Class="MyApplication.MyUserControl">
<local:MyGroupBox Title="Basic Information">
<TextBox x:Name="MyTextBox" />
</local:MyGroupBox>
</UserControl>
当我尝试从后面的页面代码中访问 MyTextBox 时,成员变量为空。在这种情况下,访问这些控件以便我可以在后面的页面代码中使用它们的最佳解决方法是什么?
谢谢!
编辑:这是 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");
}
}