【问题标题】:Control created in Custom Layout Control returns Null在自定义布局控件中创建的控件返回 Null
【发布时间】: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


    【解决方案1】:

    尝试将MyRichTextBox 放入某种Panel 中(StackPanelGrid 等)。

    编辑:实际上,为什么不在StackPanel 开头?如果您想要一些层次结构,请为工具栏使用嵌套的StackPanel 外部StackPanel

    另一个编辑:我现在不能将它复制到一个项目中来尝试它,但是这条线:this.LayoutRoot.Children 返回你认为它的作用吗?

    【讨论】:

    • 就像我说的,一旦超出我的布局控制,它就可以在其他地方工作。当然我会使用 StackPanel 或 Grid 来做同样的事情,但我创建的这个布局控件只是为我的测试提供标准布局。
    • 刚刚注意到,您是否尝试从 MainPage.xaml.cs 而不是 KTopContentBottomLayout 访问 MyRichTextBox?它没有在 MainPage 中定义,它在用户控件中。
    • 是的,但是如果我做同样的事情来让在 StackPanel 中定义的 MyRichTextBox 它仍然可以工作......是的,this.LayoutRoot.Children 确实返回了我想要的。
    • 我不明白你在说什么。你是说如果你把richtextbox放在堆栈面板中,它会起作用吗?如果是这样,问题就解决了。
    • 我的意思是,如果我不使用自己的布局控件,但使用 Stack/Grid 它将起作用。这里的问题是,当我在自定义布局控件中创建“控件”时,“控件”将返回 null...
    猜你喜欢
    • 2013-08-24
    • 1970-01-01
    • 1970-01-01
    • 2019-08-16
    • 2010-12-19
    • 2014-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多