wpf 依赖属性的值约束

在依赖属性中,值的约束不能单一的从Set方法中操作

 public int MyProperty
        {
            get { return (int)GetValue(MyPropertyProperty); }
            set { SetValue(MyPropertyProperty, value); }
        }

        // Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty MyPropertyProperty =
            DependencyProperty.Register("MyProperty",
                typeof(int),
                typeof(CustomControl1),
                new FrameworkPropertyMetadata(0, FrameworkPropertyMetadataOptions.AffectsMeasure, OnMyPropertyChanged, OnCoerceMyPropertyChanged),
                new ValidateValueCallback(IsValidValue));

        /// <summary>
        /// 对输入的值做约束
        /// </summary>
        /// <param name="d"></param>
        /// <param name="baseValue"></param>
        /// <returns></returns>
        private static object OnCoerceMyPropertyChanged(DependencyObject d, object baseValue)
        {
            Console.WriteLine($"OnCoerceMyPropertyChanged {baseValue}");
            var newValue = (int)baseValue;
            if (newValue > 250)
            {
                return 249;
            }
            return baseValue;
        }

        /// <summary>
        /// 返回false,则会抛出异常,
        /// 这里不会参考OnCoerceMyPropertyChanged更改的值,依然为原始的输入,
        /// 如果使用了OnCoerceMyPropertyChanged 则不需要使用本回调
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool IsValidValue(object value)
        {
            return true;
            var newValue = (int)value;
            return newValue < 500;
        }
        private static void OnMyPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            Console.WriteLine($"OnMyPropertyChanged {e.NewValue}");
        }
posted @ 2023-02-19 12:41  trykle  阅读(51)  评论(0)    收藏  举报