如何让DependencyProperty在Silverlight中工作?

时间:2012-02-29 23:59:28

标签: silverlight dependency-properties

我正在尝试使用DependencyProperty绑定,但我甚至无法让DependencyProperty工作,更不用说尝试绑定它了。

我正在关注Silverlight指南,到目前为止我应该能够使用XAML设置属性。这是我到目前为止的代码:

MainPage.xaml中:

<UserControl
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"
xmlns:local="clr-namespace:UserControlSample" x:Class="UserControlSample.MainPage"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">

<Grid x:Name="LayoutRoot" Background="White">
    <local:InfoRectangle Margin="32,36,0,0" HorizontalAlignment="Left" Height="70" VerticalAlignment="Top" Width="122" InfoText="New Text"/>
    <local:InfoRectangle Margin="105,139,188,97" InfoText="some text" />
</Grid>

InfoRectangle.xaml:

<UserControl
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"
xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
mc:Ignorable="d"
x:Class="UserControlSample.InfoRectangle"
d:DesignWidth="122" d:DesignHeight="70">

<Grid x:Name="LayoutRoot">
    <Rectangle Fill="#FFABABE9" Stroke="Black" RadiusY="4" RadiusX="4"/>
    <TextBlock Name="InfoLabel" Text="Text block" Margin="5" />
</Grid>

InfoRectangle.xaml.cs:

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace UserControlSample
{
public partial class InfoRectangle : UserControl
{
    public InfoRectangle()
    {
        // Required to initialize variables
        InitializeComponent();
    }

    public string InfoText
    {
        get { return (string)GetValue(InfoTextProperty); }
        set { SetValue(InfoTextProperty, value); }
    }

    public static readonly DependencyProperty InfoTextProperty =
        DependencyProperty.Register(
            "InfoText",
            typeof(string),
            typeof(InfoRectangle),
            new PropertyMetadata("something", InfoTextChanged));

    private static void InfoTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
    }
}
}

当我运行解决方案时,两个矩形显示但它们只显示“文本块”,它既不是默认设置,也不是MainPage XAML中为用户控件设置的值。

2 个答案:

答案 0 :(得分:1)

我在here中的回答详细介绍了一个很好的紧凑型示例,它描述了一个依赖属性更新视图模型上的给定属性。视图模型上的属性将绑定到您的文本块,因此一旦更改通知触发,您的文本块就会更新。

答案 1 :(得分:0)

这是解决方案;

似乎必须完成回调方法。

private static void InfoTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    ((InfoRectangle)d).InfoLabel.Text = e.NewValue.ToString();
}