【发布时间】:2011-10-27 16:15:38
【问题描述】:
我有一个 WP7 silverlight 项目。我有一个“用户控件”来显示基于 DependencyProject 的矩形。
现在,当我将控件放在我的页面上时:
<uc:RectangleControl NumRectangles={Binding Path=RectangleCount,Mode=OneWay} />
我根据“RectangleCount”的初始值显示我的矩形。但是,当 RectangleCount 更改时,用户控件永远不会更新。我预计这是由于我在 OnLoaded 事件中绘制矩形引起的,但我无法终生找到另一个要绑定的事件以导致控件在 NumRectangles DP 更新时绘制新矩形。
有什么帮助吗?
用户控件 XAML:
<UserControl x:Class="WP7Test.Controls.RectangleControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
d:DesignHeight="80" d:DesignWidth="480">
<Canvas x:Name="canvas"
Height="{Binding Height}" Width="{Binding Width}">
</Canvas>
</UserControl>
在后面的代码中,我根据依赖属性添加了矩形:
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 WP7Test.Controls
{
public partial class RectangleControl : UserControl
{
private double RectangleSpacing = 1;
#region Dependency Properties
public int NumRectangles
{
get { return (int)GetValue(NumRectanglesProperty); }
set { SetValue(NumRectanglesProperty, value); }
}
// Using a DependencyProperty as the backing store for NumRectangles. This enables animation, styling, binding, etc...
public static readonly DependencyProperty NumRectanglesProperty =
DependencyProperty.Register("NumRectangles", typeof(int), typeof(RectangleControl), new PropertyMetadata(5));
#endregion
public RectangleControl()
{
InitializeComponent();
Loaded += new RoutedEventHandler(OnLoaded);
}
private void OnLoaded(object sender, RoutedEventArgs args)
{
double rectangleWidth = 20;
double rectangleHeight = 20;
double x = 0;
double y = 0;
for (int i = 0; i < NumRectangles; i++)
{
Brush b = new SolidColorBrush(Colors.Red);
Rectangle r = GenerateRectangle(x, y, rectangleWidth, rectangleHeight, b);
canvas.Children.Add(r);
x += rectangleWidth + 1;
}
}
public Rectangle GenerateRectangle(double x, double y, double width, double height, Brush brush)
{
Rectangle r = new Rectangle();
r.Height = height;
r.Width = width;
r.Fill = brush;
Canvas.SetLeft(r, x);
Canvas.SetTop(r, y);
return r;
}
}
}
【问题讨论】:
标签: silverlight windows-phone-7 dependency-properties