我想学习如何使用依赖对象和属性。我创建了这个类,
public class TestDependency : DependencyObject
{
public static readonly DependencyProperty TestDateTimeProperty =
DependencyProperty.Register("TestDateTime",
typeof(DateTime),
typeof(TestDependency),
new PropertyMetadata(DateTime.Now));
public DateTime TestDateTime
{
get { return (DateTime) GetValue(TestDateTimeProperty); }
set { SetValue(TestDateTimeProperty, value); }
}
}
窗口类是这样的
public partial class MainWindow : Window
{
private TestDependency td;
public MainWindow()
{
InitializeComponent();
td = new TestDependency();
td.TestDateTime = DateTime.Now;
}
}
现在我想用它来显示 TextBlock 中的当前 DateTime ,它每秒更新一次,方法是将它添加到网格中
<Grid>
<TextBlock Text="{Binding TestDateTime,ElementName=td}" Width="200" Height="200"/>
</Grid>
我可以看到 TextBlock,但其中根本没有 Date Time 值。我究竟做错了什么?