views:

45

answers:

2

I have a silverlight custom control named "BASE". I have another control that inherits from this class, "CHILD1". BASE has a ContentPresenter that holds the content from the CHILD1 control. I need to access a TextBox that is in the content of the CHILD1 control, it initiailzes, and displays, but it is always null in the code.

Is there a way to access these controls directly instead of iterating over the children collection of the content property?

Thanks.

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();
    }
}

Part of BASE:

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

Base class code:-

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

Is the TextBox still null if you tried to focus it in the OnApplyTemplate override instead of the constructor?

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

    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
        this.tbx1.Focus();
    }
}
Dan Auclair
Yes, it is still null.
Sako73
A: 

I don't think it should be this difficult, but here is the work around that I got to work:

[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();
    }
}

I am still very interested in hearing what the technically correct solution is.

Sako73