我正在尝试使用附加属性来专门设置网格的左边距。可悲的是,它不起作用。该属性引发 XamlParseException“默认值类型与属性类型不匹配”。
我的附属财产
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
}
我的用户界面
<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>