重构附属物

时间:2012-03-05 17:38:16

标签: wpf xaml attached-properties

我正在尝试将下面的代码从事件设置器更改为附加属性(这样我就可以清理后面的代码)。我在setter中得到一个错误,说该值不能为null,但我不明白为什么。

忘记这是否是一个好主意,有人可以帮助我获得附属财产吗?

干杯,
Berryl

EventSetter(可以使用但后面带有代码)

    <!-- SINGLE CLICK EDITING -->
    <Style TargetType="{x:Type DataGridCell}">
        <EventSetter Event="PreviewMouseLeftButtonDown" Handler="OnPreviewMouseLeftButtonDown"/>
    </Style>

private void OnPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    var cell = sender as DataGridCell;
    cell.Activate();
}

属性设置器(错误)

<!-- SINGLE CLICK EDITING -->
<Style TargetType="{x:Type DataGridCell}">
    <Setter Property="begavior:DataGridCellProperties.SingleClickToEdit" Value="True"/>
</Style>

public class DataGridCellProperties
{
    public static readonly DependencyProperty SingleClickToEditProperty =
        DependencyProperty.RegisterAttached("SingleClickToEditProperty",
                                            typeof(bool), typeof(DataGridCellProperties),
                                            new PropertyMetadata(false, OnSingleClickToEditPropertyChanged));

    [AttachedPropertyBrowsableForChildren(IncludeDescendants = false)]
    [AttachedPropertyBrowsableForType(typeof(DataGridCell))]
    public static bool GetSingleClickToEdit(DataGridCell obj) { return (bool)obj.GetValue(SingleClickToEditProperty); }

    public static void SetSingleClickToEdit(DataGridCell obj, bool value) { obj.SetValue(SingleClickToEditProperty, value); }

    private static void OnSingleClickToEditPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
    {
        var sender = obj as UIElement;
        if (sender == null) return;

        if ((bool)e.NewValue)
        {
            sender.PreviewMouseLeftButtonDown += OnPreviewMouseLeftButtonDown_EditCell;
        }
        else
        {
            sender.PreviewMouseLeftButtonDown -= OnPreviewMouseLeftButtonDown_EditCell;
        }
    }

    private static void OnPreviewMouseLeftButtonDown_EditCell(object sender, MouseButtonEventArgs e)
    {
        var cell = sender as DataGridCell;
        cell.Activate();
    }
}

1 个答案:

答案 0 :(得分:1)

你的d-prop注册中的“SingleClickToEditProperty”应为“SingleClickToEdit”。