0
我有一個WP7 silverlight項目。我有一個'UserControl'來顯示基於DependencyProject的矩形。WP7 - 通過綁定更新用戶控件
現在,當我把我的網頁有以下的控制:
<uc:RectangleControl NumRectangles={Binding Path=RectangleCount,Mode=OneWay} />
我讓我的矩形顯示基於「RectangleCount」的初始值。但是,當更改RectangleCount時,用戶控件永遠不會更新。我期望這是由我在OnLoaded事件中繪製我的矩形引起的,但是我不能在我的生活中找到另一個綁定到的事件,以便在NumRectangles DP更新時控件繪製新的矩形。
任何幫助?
UserControl的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;
}
}
}