【问题标题】:Inheriting Silverlight 3 control does not initialize content继承 Silverlight 3 控件不初始化内容
【发布时间】:2010-04-14 15:54:17
【问题描述】:

我有一个名为“BASE”的 Silverlight 自定义控件。我有另一个从此类继承的控件“CHILD1”。 BASE 有一个 ContentPresenter,它保存来自 CHILD1 控件的内容。我需要访问 CHILD1 控件内容中的 TextBox,它会启动并显示,但它在代码中始终为 null。

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

谢谢。

孩子1:

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

部分基地:

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

【问题讨论】:

  • 关于 BASE 的详细信息不够详细,它是从什么获得的?是ContentControl 还是普通的Control
  • 它派生自 "ChildWindow" [ContentProperty("Content")] public partial class cwBase1 : ChildWindow ... new public object Content { get { return cprContent.Content; } 设置 { cprContent.Content = 值; } }
  • 很抱歉缺少格式,我似乎无法在评论中找到换行符。
  • @sako73:那是因为您应该将代码放在您的问题中,而不是在评论中。看到问题下的编辑链接了吗?

标签: silverlight silverlight-3.0


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    我认为这不应该这么难,但这是我必须解决的问题:

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

    我仍然很想知道技术上正确的解决方案是什么。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多