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

问题描述:

我有一个名为“BASE”的silverlight自定义控件。我有另一个继承自这个类的控件“CHILD1”。 BASE有一个ContentPresenter,用于保存CHILD1控件的内容。我需要访问CHILD1控件内容中的文本框,它会启动并显示,但代码中始终为空。继承Silverlight 3控件不会初始化内容

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

谢谢。

CHILD1:

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

基类代码:

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

基础的一部分 -

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

没有足够的关于BASE的细节它是从哪里来的?它是一个'ContentControl'还是一个普通的'Control'? – AnthonyWJones 2010-04-14 16:22:04

+0

从 “ChildWindow” [ContentProperty( “内容”) 公共部分类cwBase1派生:ChildWindow ... 新的公共对象的内容{ 得到{cprContent.Content; } set {cprContent.Content = value; }} – Sako73 2010-04-14 17:15:06

+0

对于缺少格式化感到抱歉,我似乎无法在评论中获得换行符。 – Sako73 2010-04-14 17:16:09

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

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

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

是的,它仍然是空的。 – Sako73 2010-04-14 20:45:13

我不认为它应该是困难的,但这里的工作围绕着我的工作:

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

我仍然在听到技术上正确的解决办法是什么很感兴趣。