1

添付プロパティを使用して、グリッドの左マージンのみを設定しようとしています。残念ながら、うまくいきません。プロパティは 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>
4

4 に答える 4

0

私が間違っていない限り、添付プロパティの変更ハンドラーもデフォルト値に対して呼び出されます。nullable double を使用してみてください。UIPropertyMetadata がうまくいくかどうかはわかりません.UI固有のプロパティがいくつかあるため、場合によってはオーバーヘッドになる可能性があります。特定の Metadata オブジェクト タイプを指定せずに、デフォルトのコンストラクターのみを使用してみてください。

于 2014-04-02T15:52:32.083 に答える
0

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

于 2016-03-21T15:46:03.517 に答える