Silverlight 2.0 子控件继承返回NULL的错误到底是怎么回事

 

Tech Ed 2008开完了.我也回家了呵呵..但是这几天我一直被题目上的错误所困扰。

先说说这到底是怎么一个错误。

当我创建了新项目,加入一个Silverlight UserControl后,没有改变XAML代码,也就是保留了Grid-Layoutroot,并在CS文件中写下:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

namespace BANG

{

public partial class Container : UserControl

{

public UIElementCollection MYCHILDREN

{

get { return LayoutRoot.Children; }

set

{

/*LayoutRoot.Children is Readonly*/

LayoutRoot.Children.Clear();

foreach (var O in value)

{

LayoutRoot.Children.Add(O);

}

}

}

public Container()

{

InitializeComponent();

}

}

}

上面的那个属性相信大家已经很熟悉了。无非就是模拟Children的功能来实现Container。

在Page.XAML中我又写道:

<UserControl x:Class="BANG.Page"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

xmlns:L="clr-namespace:BANG"

Width="400" Height="300">

<Grid x:Name="LayoutRoot" Background="White">

<L:Container x:Name="Father">

<L:Container.MYCHILDREN>

<Button x:Name="button1" Content="OH YEAH"></Button>

</L:Container.MYCHILDREN>

</L:Container>

</Grid>

</UserControl>

这时 Visualstudio相当给面子的显示出我想要的结果:

clip_image002

一切似乎都很好嘛~ 于是我就嚣张的修改Page的CS

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

namespace BANG

{

public partial class Page : UserControl

{

public Page()

{

InitializeComponent();

button1.Content = "Now I died here.";

}

}

}

大家都会想象到BUTTON1的CONTENT会发生改变对巴~但一旦我PRESS F5..VS就跟我翻脸了

clip_image004

让我慢慢DEBUG进去…发现BUTTON1就是NULL?!我非常气愤…尝试使用Content Attribute来修改使它能够被检索到。但实际上是不行的。

回顾SL的工作机制,想起有xxxx.G.CS这个东西,怕是他在捣鬼,于是一气之下打开PAGE.G.CS clip_image006

发现VisualStudio犯傻了。怎么能什么都this.FindName呢?

于是将它改成Father.FindName

问题解决。但G.CS会自动复原所以我认为应该这样解决

public Page()

{

InitializeComponent();

button1 = (Button)Father.FindName("button1");

button1.Content = "Now I died here.";

}

手动建立索引就好了。

好了今天就这样了。我是新手,大家交流。

posted @ 2008-11-09 08:19  struggle-luan  阅读(1792)  评论(4编辑  收藏  举报