You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF附加属性绑定失败:无法在非依赖属性上设置Binding

Fixing WPF Attached Property Binding Error

Let's break down the issue and fix it step by step—this is a common gotcha with attached properties in WPF!

Root Cause

The main problem is a naming convention mismatch between your registered attached property and its accessor methods. WPF relies strictly on the pattern Get[PropertyName] and Set[PropertyName] to map XAML usage to the underlying dependency property. Your code had mismatched names, which confused the XAML parser.

Corrected Attached Property Code

Here's the fixed AttachedCommandBehavior class with all issues resolved:

public static class AttachedCommandBehavior
{
    #region PreviewMouseLeftButtonUpCommand
    public static readonly DependencyProperty PreviewMouseLeftButtonUpCommandProperty =
        DependencyProperty.RegisterAttached(
            "PreviewMouseLeftButtonUpCommand",
            typeof(ICommand),
            typeof(AttachedCommandBehavior),
            new FrameworkPropertyMetadata(PreviewMouseLeftButtonUpCommandChanged));

    // Correctly named accessor methods matching the property name
    public static void SetPreviewMouseLeftButtonUpCommand(DependencyObject target, ICommand value)
    {
        target.SetValue(PreviewMouseLeftButtonUpCommandProperty, value);
    }

    public static ICommand GetPreviewMouseLeftButtonUpCommand(DependencyObject target)
    {
        return (ICommand)target.GetValue(PreviewMouseLeftButtonUpCommandProperty);
    }

    // Fixed handler name and logic
    private static void PreviewMouseLeftButtonUpCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d is UIElement element)
        {
            if (e.NewValue != null && e.OldValue == null)
            {
                element.PreviewMouseLeftButtonUp += Element_PreviewMouseLeftButtonUp;
            }
            else if (e.NewValue == null && e.OldValue != null)
            {
                element.PreviewMouseLeftButtonUp -= Element_PreviewMouseLeftButtonUp;
            }
        }
    }

    private static void Element_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        if (sender is UIElement element)
        {
            if (element.GetValue(PreviewMouseLeftButtonUpCommandProperty) is ICommand command)
            {
                // Get the actual parameter value instead of the DependencyProperty object
                var parameter = element.GetValue(CommandParameterProperty);
                command.Execute(parameter);
            }
        }
    }
    #endregion

    #region CommandParameter
    public static readonly DependencyProperty CommandParameterProperty =
        DependencyProperty.RegisterAttached(
            "CommandParameter",
            typeof(object),
            typeof(AttachedCommandBehavior),
            new FrameworkPropertyMetadata(null));

    public static void SetCommandParameter(DependencyObject target, object value)
    {
        target.SetValue(CommandParameterProperty, value);
    }

    public static object GetCommandParameter(DependencyObject target)
    {
        return target.GetValue(CommandParameterProperty);
    }

    // Removed redundant CommandParameterChanged method (the DP system handles value updates automatically)
    #endregion
}

Corrected XAML Usage

Update your Border to use the correct attached property name (matching the registered property):

<Border 
    Background="{Binding BackgroundColor, Converter={StaticResource ColorNameToBrushConverter}}" 
    Cursor="{x:Static Cursors.Hand}"
    local:AttachedCommandBehavior.PreviewMouseLeftButtonUpCommand="{Binding QueryClickedCommand}"
    <!-- Optional: Add parameter if needed -->
    local:AttachedCommandBehavior.CommandParameter="{Binding YourParameterHere}">
    <Grid>...</Grid>
</Border>

Key Fixes Explained

  1. Accessor Method Naming: Renamed SetPreviewMouseLeftButtonUpChanged to SetPreviewMouseLeftButtonUpCommand to match the registered property name. This is critical—WPF can't find the attached property otherwise.
  2. Handler Name Typo: Fixed the duplicate "Preview" in the property changed handler name.
  3. Command Parameter Execution: Changed command.Execute(CommandParameterProperty) to pass the actual parameter value from the element, not the DependencyProperty object itself.
  4. Redundant Code Removal: Removed the unnecessary CommandParameterChanged method—dependency properties automatically handle value updates, so this was doing nothing useful.

This should resolve both the XAML editor error and the runtime XamlParseException.

内容的提问来源于stack exchange,提问作者jvance

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:36:11