【发布时间】:2016-11-22 07:20:04
【问题描述】:
我正在构建一个使用 DependencyProperty 和泛型的 wpf 控件,为此我需要(至少我认为)一个 CoerceValueCallback 来检查值是否正确。 这个想法是构建一个基类,我将从中派生出数字类型。
public class MyClass<T> : Control where T : struct
{
public T Value
{
get { return (T)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
// DependencyProperty as the backing store for Value
public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(
"Value",
typeof(T),
typeof(MyClass<T>),
new PropertyMetadata(null, null, CoerceValue)
);
private static object CoerceValue(DependencyObject d, object baseValue)
{
// Check if value is valid
return verifiedValue;
}
}
public class MyDerivedClass : MyClass<int>
{
}
问题是 CoerceValue 正在返回一个对象,而我找不到如何返回泛型。
有什么想法吗?
编辑:感谢以下答案,这是我所做的
public abstract class MyClass<T> : Control where T : struct, IComparable
{
public T MinValue { get; set; }
public T MaxValue { get; set; }
public T Value
{
get { return (T)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
// DependencyProperty as the backing store for Value
public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(
"Value",
typeof(T),
typeof(MyClass<T>),
new PropertyMetadata(default(T), null, CoerceValue)
);
private static object CoerceValue(DependencyObject d, object baseValue)
{
T value = (T)baseValue;
((MyClass<T>)d).CoerceValueToBounds(ref value);
return value;
}
private void CoerceValueToBounds(ref T value)
{
if (value.CompareTo(MinValue) < 0)
value = MinValue;
else if (value.CompareTo(MaxValue) > 0)
value = MaxValue;
}
}
这样,我可以将 Value 限制在 MinValue 和 MaxValue 之内,并使所有内容都保持泛型,从而避免在每个派生类中重写抽象方法。
【问题讨论】:
-
将返回值更改为
T时发生了什么? -
在什么意义上“返回泛型”?
-
"private static T CoerceValue(DependencyObject d, object baseValue) { // 检查值是否有效 return verifyValue; }" 这样,Visual Studio 告诉我该方法的返回类型错误跨度>
-
这里的值怎么会无效?您不需要 CoerceValueCallback。
-
该值必须保持在给定范围内。 Corcevalue 应该检查
标签: c# wpf generics dependency-properties