WPF - 在另一个属性的Setter中更改属性值

时间:2017-07-04 09:31:58

标签: c# wpf wpf-controls dependency-properties

在我的自定义控件的以下示例中,为什么我无法更改 setter 中的 TransparentColor 属性SelectedColor 属性?使用回调方法的解决方案工作正常,在更改另一个属性的情况下它们之间的区别是什么?

public class MyColorPicker : Control
{
    static MyColorPicker()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(MyColorPicker), new FrameworkPropertyMetadata(typeof(MyColorPicker)));
    }

    public static readonly DependencyProperty SelectedColorProperty =
            DependencyProperty.Register("SelectedColor", typeof(Color), typeof(MyColorPicker), new PropertyMetadata(Color.FromRgb(0, 201, 201), OnSelectedColorChange));

    private static void OnSelectedColorChange(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        var colorPicker = (MyColorPicker)sender;
        var selectedColor = colorPicker.SelectedColor;
        colorPicker.TransparentColor = Color.FromArgb(0, selectedColor.R, selectedColor.G, selectedColor.B);
    }

    public Color SelectedColor
    {
        get { return (Color)GetValue(SelectedColorProperty); }
        set
        {
            // Why this not working? BorderStopColor = Color.FromArgb(0, value.R, value.G, value.B);
            SetValue(SelectedColorProperty, value);
        }
    }

    private static readonly DependencyPropertyKey TransparentColorPropertyKey =
            DependencyProperty.RegisterReadOnly("TransparentColor", typeof(Color), typeof(MyColorPicker), new PropertyMetadata(Color.FromArgb(0, 0, 201, 201)));

    public static readonly DependencyProperty TransparentColorProperty = TransparentColorPropertyKey.DependencyProperty;

    public Color TransparentColor
    {
        get { return (Color)GetValue(TransparentColorProperty); }
        protected set { SetValue(TransparentColorPropertyKey, value); }
    }
}

1 个答案:

答案 0 :(得分:1)

依赖项属性的CLR包装器的setter应调用SetValue方法来设置依赖项属性的实际值。

任何其他逻辑都应该在回调中实现。

另请注意,在XAML中设置依赖项属性时,会在运行时绕过CLR属性包装器(但回调不是):

Why are .NET property wrappers bypassed at runtime when setting dependency properties in XAML?