Search code examples
c#wpfattached-propertiesxamlparseexception

Attached property not accepting default value for double


I'm trying to use an attached property to set the left margin of a grid exclusively. Sadly, it doesn't work. The property throws a XamlParseException "Default value type does not match type of property".

My attached property

public class Margin : DependencyObject
{
    #region Dependency Properties
    public static readonly DependencyProperty LeftProperty =
        DependencyProperty.RegisterAttached("Left", typeof(double), typeof(Margin),
        new PropertyMetadata(new UIPropertyMetadata(0d, OnMarginLeftChanged)));
    #endregion

    #region Public Methods
    public static double GetLeft(DependencyObject obj)
    {
        return (double)obj.GetValue(LeftProperty);
    }
    public static void SetLeft(DependencyObject obj, double value)
    {
        obj.SetValue(LeftProperty, value);
    }
    #endregion

    #region Private Methods
    private static void OnMarginLeftChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
    {
        var element = obj as FrameworkElement;
        var margin = element.Margin;
        margin.Left = (double)e.NewValue;
        element.Margin = margin;
    }
    #endregion
}

My user Interface

<Window x:Class="MSPS.View.Test.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:ctrl="clr-namespace:MSPS.View.Controls;assembly=MSPS.View.Controls"
        xmlns:ap="clr-namespace:MSPS.View.Controls.AttachedProperties;assembly=MSPS.View.Controls"
        Title="MainWindow" Height="350" Width="525">
    <Grid Background="Blue" ap:Margin.Left="20">

    </Grid>
</Window>

Solution

  • You not correctly set PropertyMetadata, in this case you two times create the instance of this class:

    DependencyProperty.RegisterAttached("Left", typeof(double), typeof(Margin),
        new PropertyMetadata(new UIPropertyMetadata(0d, OnMarginLeftChanged)));
    

    Should be so:

    DependencyProperty.RegisterAttached("Left", typeof(double), typeof(Margin),
        new UIPropertyMetadata(0.0, OnMarginLeftChanged));
    

    Or like this:

    DependencyProperty.RegisterAttached("Left", typeof(double), typeof(Margin),
        new PropertyMetadata(0d, OnMarginLeftChanged));