UserControl的构造函数

时间:2018-01-19 12:49:17

标签: c# wpf

我有自己的WPF UserControl(例如Image + ViewBox - 没关系)。该控件具有布尔值依赖属性,例如NeedToDrawRect。我想要实现的目标:当用户将(在XAML中)此属性设置为true时,我需要执行一些操作 - 但只需执行一次。 我打算在c-tor中执行这个动作,但似乎我在那个阶段看不到这个属性值:

XAML:

<pzi:PanZoomImage Grid.Row="1" Grid.Column="0" NeedToDrawRect="True" />

UserControl构造函数:

public PanZoomImage()
{
    InitializeComponent();

    LayoutRoot.DataContext = this;

    // Here NeedToDrawRect is still false
    if (NeedToDrawRect)
           DoSmth();            
}

那么,我在哪里可以检查用户在XAML中设置的值。当然我可以覆盖OnRender并每次检查,但我想使用正确的方式来做到这一点。

2 个答案:

答案 0 :(得分:4)

为依赖项属性注册PropertyChangedCallback

public static readonly DependencyProperty NeedToDrawRectProperty = DependencyProperty.Register(nameof(NeedToDrawRect),
    typeof(bool), typeof(PanZoomImage ), new PropertyMetadata(new PropertyChangedCallback(OnValueChanged)));

public bool NeedToDrawRect
{
    get { return (bool)GetValue(NeedToDrawRectProperty); }
    set { SetValue(NeedToDrawRectProperty, value); }
}

private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    var ctrl = (PanZoomImage)d;
    var newValue = (bool)e.NewValue;
    //...
}

只要依赖属性设置为新值,就会调用回调。

如果您只想做一次,可以使用私有字段来跟踪之前是否已调用回调,例如:

private int n;

private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    if (n++ > 0)
    {
        var ctrl = (PanZoomImage)d;
        var newValue = (bool)e.NewValue;
        //...
    }
}

答案 1 :(得分:-1)

您可以在创建依赖项属性时使用 PropertyChangedCallback 。如果您希望它仅在ONCE上执行,然后不允许用户更改它,您可以尝试在PropertyChangedCallback中对其进行操作。

    public bool NeedToDrawRect
    {
        get { return (bool)GetValue(NeedToDrawRectProperty); }
        set
        {
            SetValue(NeedToDrawRectProperty, value);
        }
    }


    public static readonly DependencyProperty NeedToDrawRectProperty =
        DependencyProperty.Register("NeedToDrawRect",
            typeof(bool),
            typeof(PanZoomImage),
            new PropertyMetadata(false, OnNeedToDrawRectChanged ));

    private static void OnNeedToDrawRectChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var control = d as PanZoomImage;
        if (control!=null && (bool)e.NewValue == false && (bool)e.OldValue == true)
        {
            control.NeedToDrawRect = true; // user won't be able to set it to false again.
        }
    }

这应该有效。如果您使用复选框执行操作,请将复选框的 IsReadOnly 属性绑定到属性 NeedToDrawRect ,以便用户将其设置为true后,用户赢了&# 39;能够再次改变它。您可能需要 InverseBooleanConverter 才能执行此操作。