【问题标题】:Dependency property not updating usercontrol ui依赖属性不更新用户控件 ui
【发布时间】:2011-12-24 04:31:30
【问题描述】:

我有一个用户控件,上面有几个文本块

<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 项集合中时,这些不会反映在控件中。该控件仅显示 Header 和 Message 的默认值。

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

【问题讨论】:

    标签: wpf silverlight user-controls dependency-properties


    【解决方案1】:

    您对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 也是如此。

    【讨论】:

    • 当我第一次开始做 WPF 时 - 这让我受了太多次了!
    • 是的,非常感谢。犯的愚蠢错误。看了很久,没看明白。再次感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多