DependencyProperty - 如何设置值的步进变化?

时间:2013-10-21 10:12:13

标签: wpf xaml dependency-properties

我为UserControl创建了一个DependencyProperty,它应该在-2 .. 2

的范围内

在属性窗口中旋转鼠标滚轮时。 属性值更改为1。我希望价值改变0.1 如何在DependencyProperty中设置步骤更改? 我在XAML编辑器中使用属性。

 public double Value
        {
            get { return (double)GetValue(BarValueProperty); }
            set { SetValue(BarValueProperty, value); }
        }


        public static readonly DependencyProperty BarValueProperty =
        DependencyProperty.Register("Value", typeof(double), typeof(MeterBar), new FrameworkPropertyMetadata(0.0, FrameworkPropertyMetadataOptions.AffectsRender));

1 个答案:

答案 0 :(得分:0)

FrameworkPropertyMetadata选项添加到DependencyProperty的定义中时,可以选择提供CoerceValueCallback处理程序。您可以在此处理程序中更改incomming值。有关完整的详细信息,请参阅MSDN上的Dependency Property Callbacks and Validation页面。从链接页面:

public static readonly DependencyProperty CurrentReadingProperty = 
    DependencyProperty.Register(
    "CurrentReading",
    typeof(double),
    typeof(Gauge),
    new FrameworkPropertyMetadata(
        Double.NaN,
        FrameworkPropertyMetadataOptions.AffectsMeasure,
        new PropertyChangedCallback(OnCurrentReadingChanged),
        new CoerceValueCallback(CoerceCurrentReading)
    ),
    new ValidateValueCallback(IsValidReading)
);
public double CurrentReading
{
  get { return (double)GetValue(CurrentReadingProperty); }
  set { SetValue(CurrentReadingProperty, value); }
}

...

private static object CoerceCurrentReading(DependencyObject d, object value)
{
    // Do whatever calculation to update your value you need to here
    Gauge g = (Gauge)d;
    double current = (double)value;
    if (current
            <g.MinReading) current = g.MinReading;
    if (current >g.MaxReading) current = g.MaxReading;
    return current;
}