WPF CoerceCallback 取消值更改

WPF CoerceCallback to cancel value change

我有一个文本框数据绑定到一个字符串,UpdateSourceTrigger = PropertyChanged。我只想允许用户在文本框中输入整数。我还希望整数值的最小值为 0,最大值为 60。

此代码仅适用于限制整数范围。经过一些测试后,我意识到如果我 return 旧值 CoerceValueCallback 不起作用。也就是说,我无法取消 属性 更改。有什么方法可以解决这种或另一种类型的元数据,效果更好吗?

我已尝试使用 DependencyProperty.UnsetValue 取消更改,如 'Using CoerceValue to Cancel Value Changes' 中所述。这是行不通的。 https://docs.microsoft.com/en-us/dotnet/framework/wpf/advanced/dependency-property-callbacks-and-validation

        public static object CoerceValueCallback(DependencyObject d, object value)
        {
            var uc = (UserControlConnection)d;
            string s = (string)value;

            if (int.TryParse(s, out int i))
            {
                i = Math.Min(i, 60);
                i = Math.Max(i, 0);
                uc.TimeoutSeconds = i;
            }
            return uc.TimeoutSeconds.ToString();
        }

显然问题与使用文本框和 UpdateSourceTrigger = PropertyChanged 有关。以下作品。

<TextBox Text="{Binding TimeoutSecondsString, ElementName=Parent_UC, UpdateSourceTrigger=Explicit}" TextChanged="Textbox_TextChanged"/>

private void Textbox_TextChanged(object sender, TextChangedEventArgs e)
{
   var be = ((TextBox)sender).GetBindingExpression(TextBox.TextProperty);
   if (be != null)
   { be.UpdateSource(); }
}

public static object CoerceValueCallback(DependencyObject d, object value)
{
   var uc = (UserControlConnection)d;
   string s = (string)value;

   if (int.TryParse(s, out int i))
   {
       i = Math.Min(i, 60);
       i = Math.Max(i, 0);
       uc.TimeoutSeconds = i;
       return uc.TimeoutSeconds.ToString();
   }
   return DependencyProperty.UnsetValue;
}
```