我使用Visual Studio 2008的Silverlight中2.0的最新版本我有下面的代码一个简单的Silverlight用户控件:刷新Silverlight的用户控件通过XAML
public partial class SilverlightControl1 : UserControl
{
public SilverlightControl1()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(SilverlightControl1_Loaded);
Composite = new Composite();
}
void SilverlightControl1_Loaded(object sender, RoutedEventArgs e)
{
Composite.Width = this.Width/2.0;
Composite.Height = this.Height/2.0;
if (!this.LayoutRoot.Children.Contains(Composite))
this.LayoutRoot.Children.Add(Composite);
}
public Composite Composite
{
get;
set;
}
}
public class Composite : ContentControl
{
private Grid grid;
private Canvas canvas;
public Composite()
{
if (grid == null) grid = new Grid();
if (canvas == null) canvas = new Canvas();
if (!grid.Children.Contains(canvas))
grid.Children.Add(canvas);
Content = grid;
this.Loaded += new RoutedEventHandler(Composite_Loaded);
}
private Rectangle rectangle;
void Composite_Loaded(object sender, RoutedEventArgs e)
{
if (rectangle == null) rectangle = new Rectangle();
Canvas.SetTop(rectangle, 0);
Canvas.SetLeft(rectangle, 0);
rectangle.Fill = new SolidColorBrush(Color);
rectangle.Width = Width;
rectangle.Height = Height;
if (!canvas.Children.Contains(rectangle))
canvas.Children.Add(rectangle);
}
public Color Color
{
get;
set;
}
}
然后我在Silverlight应用程序使用此用户控件,在页面的XAML看起来像这样:
<UserControl x:Class="SilverlightApplication1.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:test="clr-namespace:SilverlightClassLibrary1;assembly=SilverlightClassLibrary1"
Width="400" Height="300">
<Grid x:Name="LayoutRoot" Background="Green">
<test:SilverlightControl1 Name="uControl1">
<test:SilverlightControl1.Composite>
<test:Composite Color="Yellow"/>
</test:SilverlightControl1.Composite>
</test:SilverlightControl1>
</Grid>
</UserControl>
我的问题是:我有什么代码添加到上面,这样通过改变“综合色”到黄色之外的东西,打的返回按钮, UserControl会自动刷新?正如代码所示,刷新UserControl的唯一方法是通过移动VS2008 IDE中的Slider栏来改变Silverlight页面的缩放百分比。一个侧面的问题,尽管对上述问题不太重要,但是:如上面的代码,为什么我不能更改LayoutRoot的“背景”颜色?如果我删除我的UserControl它按预期工作。
感谢您的回答,科雷尔!正如你所建议的那样,我已经将Composite和Color属性实现为依赖属性,但不幸的是,这对问题没有任何影响! – 2009-05-26 14:36:11