>我有一个用户控件,上面有几个文本块
<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"/>
在我的代码隐藏中,我有两个依赖项属性,我将上面的文本块 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 的对象并更改标头和消息属性并将控件放在 ItemControls 项集合中时,这些属性不会反映在控件中。该控件仅显示标头和消息的默认值。
Messenger m = new Messenger();
m.Header = "colin";
m.Message = "Download File ?";
iControl.Items.Add(m);
调用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 中,即不带"属性"后缀。您的信息也是如此 DependencyProperty
.