我正在构建一个简单的 UserControl,名为 DoubleDatePicker,它定义了一个 DependencyProperty,名为 SelectedDate:
DoubleDatePicker.xaml:
<UserControl x:Class="TestWpfDoubleDatePicker.DoubleDatePicker"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:toolkit="http://schemas.microsoft.com/wpf/2008/toolkit">
<StackPanel x:Name="LayoutRoot" Background="White">
<toolkit:DatePicker x:Name="DateInput" SelectedDate="{Binding SelectedDate,Mode=TwoWay}" Margin="5,0,5,0" />
<TextBlock Text="{Binding SelectedDate}" />
<toolkit:DatePicker SelectedDate="{Binding SelectedDate,Mode=TwoWay}" Margin="5,0,5,0" />
</StackPanel>
DoubleDatePicker.xaml.cs :
using System;
using System.Windows;
using System.Windows.Controls;
namespace TestWpfDoubleDatePicker
{
public partial class DoubleDatePicker : UserControl
{
public static readonly DependencyProperty SelectedDateProperty =
DependencyProperty.Register("SelectedDate", typeof(DateTime), typeof(DoubleDatePicker), null);
public DateTime SelectedDate
{
get { return (DateTime)this.GetValue(SelectedDateProperty); }
set { this.SetValue(SelectedDateProperty, value); }
}
public DoubleDatePicker()
{
this.InitializeComponent();
this.DataContext = this;
}
}
}
我希望能够从外部绑定 SelectedDate 属性,但事情似乎并不那么简单。
这是一段示例代码,试图在 TextBlock 中获取该属性的值:
MainWindow.xaml:
<Window x:Class="TestWpfDoubleDatePicker.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TestWpfDoubleDatePicker"
Title="MainWindow" Height="350" Width="525">
<StackPanel x:Name="LayoutRoot" Background="White">
<local:DoubleDatePicker x:Name="ddp" SelectedDate="{Binding SelectedDate}" />
<Button Content="Update" Click="Button_Click" />
<TextBlock Text="{Binding SelectedDate}" />
</StackPanel>
以及 MainWindow.xaml.cs 文件:
using System;
using System.Windows;
namespace TestWpfDoubleDatePicker
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public static readonly DependencyProperty SelectedDateProperty =
DependencyProperty.Register("SelectedDate", typeof(DateTime), typeof(MainWindow), null);
public DateTime SelectedDate
{
get { return (DateTime)this.GetValue(SelectedDateProperty); }
set { this.SetValue(SelectedDateProperty, value); }
}
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
this.SelectedDate = this.ddp.SelectedDate;
}
}
}
在 DoubleDatePicker 内部,一切都运行良好:当使用任意一个 DatePicker 时,SelectedDate 属性会被更新,并且 DoubleDatePicker 的 TextBlock 也会按预期更新。
但是,在外部,MainWindow 的 TextBlock 不会自动更新,获取 DoubleDatePicker 的 SelectedDate 属性的唯一方法是显式获取,就像点击 Button 时所做的那样。
我做错了什么?
我正在使用带有 WPF 4 的 Visual Studio Professional 2010。
提前感谢您的帮助。