我目前正在尝试创建一个DataGridTemplateColumn可以在我们的许多应用程序中重用的自定义控件.我遇到了一些问题,在自定义控件上获取依赖属性以进行绑定并正确引发属性更改通知.
我目前有从DataGridTemplateColumnxaml 继承的控件如下所示:
<DataGridTemplateColumn x:Class="Controls.DataGridDateColumn"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock HorizontalAlignment="Left" VerticalAlignment="Center" Text="{Binding SelectedDate}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<Grid FocusManager.FocusedElement="{Binding ElementName=DatePicker}">
<DatePicker Name="DatePicker" HorizontalAlignment="Left" VerticalAlignment="Center" SelectedDate="{Binding SelectedDate}"/>
</Grid>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
Run Code Online (Sandbox Code Playgroud)
而背后的代码看起来像这样
public partial class DataGridDateColumn : DataGridTemplateColumn
{
public static readonly DependencyProperty SelectedDateProperty =
DependencyProperty.Register("SelectedDate",
typeof(DateTime?),
typeof(DataGridDateColumn),
new FrameworkPropertyMetadata(null, OnSelectedDateChanged));
private static void OnSelectedDateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
DataGridDateColumn col = (DataGridDateColumn)d;
col.SelectedDate = (DateTime?)e.NewValue;
}
public DateTime? SelectedDate {
get {
return (DateTime?)GetValue(SelectedDateProperty);
}
set …Run Code Online (Sandbox Code Playgroud)