【问题标题】:DependencyProperty - How to set a step change in value?DependencyProperty - 如何设置值的阶跃变化?
【发布时间】:2013-10-21 10:12:12
【问题描述】:

我为 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));

【问题讨论】:

    标签: wpf xaml dependency-properties


    【解决方案1】:

    FrameworkPropertyMetadata 选项添加到DependencyProperty 的定义中时,可以选择提供CoerceValueCallback 处理程序。您可以更改此处理程序中的传入值。有关完整的详细信息,请参阅 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;
    }
    

    【讨论】:

    • 据我了解是控制值的范围。但我需要从设置窗口控制步长变化。
    猜你喜欢
    • 1970-01-01
    • 2020-03-02
    • 2014-09-27
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 2016-03-18
    • 1970-01-01
    相关资源
    最近更新 更多