依赖属性不更新usercontrol ui

时间:2011-12-24 04:31:30

标签: wpf silverlight user-controls dependency-properties

我有一个usercontrol,上面有几个文本块

<UserControl x:Class="Tester.Messenger"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" 
         x:Name="myUserControl"
         >  
<TextBlock Text="{Binding ElementName=myUserControl,Path=Header,Mode=TwoWay}" Foreground="LightGray" FontSize="11"  Margin="3,3,0,-3"/>
<TextBlock Grid.Row="1" Grid.ColumnSpan="2" Text="{Binding ElementName=myUserControl,Path=Message, Mode=TwoWay}" Foreground="White" FontSize="16" Margin="3,-5"/>

在我的代码后面,我有两个依赖属性,我将上面的textblocks Text属性绑定到。

public static readonly DependencyProperty HeaderProperty =
        DependencyProperty.Register("HeaderProperty", typeof(string), typeof(UserControl), new PropertyMetadata("header"));

    public static readonly DependencyProperty MessageProperty =
        DependencyProperty.Register("MessageProperty", typeof(string), typeof(UserControl), new PropertyMetadata(null));


 public string Header
    {
        get
        {
            return (string)GetValue(HeaderProperty);
        }
        set
        {
            SetValue(HeaderProperty, value);
        }
    }

    public string Message
    {
        get
        {
            return (string)GetValue(MessageProperty);
        }
        set
        {
            SetValue(MessageProperty, value);
        }
    }

当我创建UserControl的对象并更改Header和Message属性并将控件放在ItemControls项集合中时,这些不会反映在控件中。控件只显示标题和消息的默认值。

 Messenger m = new Messenger();
        m.Header = "colin";
        m.Message = "Download File ?";
        iControl.Items.Add(m);

1 个答案:

答案 0 :(得分:4)

您对DependencyProperty.Register的调用中的第一个参数不正确:

public static readonly DependencyProperty HeaderProperty =
        DependencyProperty.Register("HeaderProperty", typeof(string), typeof(UserControl), new PropertyMetadata("header"));

应该是:

public static readonly DependencyProperty HeaderProperty =
        DependencyProperty.Register("Header", typeof(string), typeof(UserControl), new PropertyMetadata("header"));

字符串应该是属性的名称,因为它将出现在XAML中,即没有“Property”后缀。您的邮件DependencyProperty也是如此。