【发布时间】:2012-07-03 18:10:18
【问题描述】:
我正在尝试创建自己的自定义布局控件,因此我创建了一个 UserControl,如下所示:
public partial class KTopContentBottomLayout : UserControl
{
Orientation _Orientation = Orientation.Vertical;
public Orientation Orientation { get { return this._Orientation; } set { this._Orientation = value; } }
public UIElementCollection Children
{
get
{
return this.LayoutRoot.Children;
}
}
public KTopContentBottomLayout()
{
InitializeComponent();
CreateProperLayout();
}
//Some other code that creates the layouts
}
然后在我使用这个控件的 MainPage.xaml 中:
<Grid x:Name="LayoutRoot" Background="White">
<local:KTopContentBottomLayout Orientation="Vertical" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<local:KTopContentBottomLayout.Children>
<StackPanel>
<c1:C1RichTextBoxToolbar RichTextBox="{Binding ElementName=MyRichTextBox}"/>
</StackPanel>
<c1:C1RichTextBox x:Name="MyRichTextBox" ReturnMode="HardLineBreak" />
</local:KTopContentBottomLayout.Children>
</local:KTopContentBottomLayout>
</Grid>
到目前为止,一切都可以正常编译并正确显示。 但是当我尝试在 Loaded 事件中使用控件时:
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
this.MyRichTextBox.GotFocus += MyRichTextBox_GotFocus;
this.MyRichTextBox.LostFocus += MyRichTextBox_LostFocus;
}
MyRichTextBox 对象返回 null...
我尝试将控件从我的自定义布局控件中移出,并且工作正常。那我做错了什么?
编辑:
我注意到如果我通过KTopContentBottomLayout 访问MyRichTextBox,我可以正确访问MyRichTextBox。
即使用 Children.First() 等创建属性/访问权限。
但我不明白为什么如果我在MainPage.xaml 中直接访问MyRichTextBox 会给我null。
如果我将KTopContentBottomLayout替换为Grid/StackPanel,他们可以直接访问MyRichTextBox,但这是什么原因呢?
【问题讨论】:
标签: c# wpf xaml silverlight c1richtextbox