继承Silverlight 3控件不会初始化内容

时间:2010-04-14 15:54:17

标签: silverlight silverlight-3.0

我有一个名为“BASE”的silverlight自定义控件。我有另一个继承自这个类的控件,“CHILD1”。 BASE有一个ContentPresenter,它保存CHILD1控件的内容。我需要访问一个位于CHILD1控件内容中的TextBox,它会初始化并显示,但在代码中它总是为空。

有没有办法直接访问这些控件而不是迭代内容属性的子集合?

感谢。

CHILD1:

<local:BASE x:Class="CWTest1.CHILD1"
           xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
           xmlns:local="clr-namespace:CWTest"
           xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
           Width="400"
           Height="300">
<Grid x:Name="LayoutRoot2"
      Background="White">
    <TextBox x:Name="tbx1"
             Text="xx" />
</Grid>

public partial class CHILD1 : BASE
{
    public CHILD1()
    {
        InitializeComponent();

        // this.tbx1 is always null
        this.tbx1.Focus();
    }
}

BASE的一部分:

<ContentPresenter Grid.Row="1"
                      x:Name="cprContent"
                      Content="" />

基类代码: -

[ContentProperty("Content")]
public partial class cwBase1 : ChildWindow
...
new public object Content
    {
        get { return cprContent.Content; }
        set { cprContent.Content = value; }
    }

2 个答案:

答案 0 :(得分:0)

如果你试图将它集中在OnApplyTemplate覆盖而不是构造函数上,TextBox是否仍然为空?

public partial class CHILD1 : BASE
{
    public CHILD1()
    {
        InitializeComponent();
    }

    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
        this.tbx1.Focus();
    }
}

答案 1 :(得分:0)

我认为这不应该是困难的,但这是我开始工作的工作:

[ContentProperty("Content2")]
public partial class cwBase1 : ChildWindow
{
    ....
    public object Content2
    {
        get { return cprContent.Content; }
        set { cprContent.Content = value; }
    }
    ....
    protected T GetUIElement<T>(string name)
    {
        UIElement el = ((Grid)this.Content2).Children.FirstOrDefault(ui => 
            ui.GetType() == typeof(T) && 
            ui.GetType().GetProperty("Name").GetValue(ui, null).ToString() == name);

        return (T)(object)el;
    }
}




public partial class inherit2 : cwBase1
{
    public inherit2()
    {
        InitializeComponent();
        GetUIElement<TextBox>("tbx1").Focus();
    }
}

我仍然非常有兴趣了解技术上正确的解决方案。