I have a WPF control that comes from shared databases. For example: IntegerUpDown from CommonNumericUpDown from NumericUpDown from UpDownBase.
UpDownBase has a static property declared as:
public static readonly DependencyProperty ValueProperty = DependencyProperty.Register( "Value", typeof( T ), typeof( UpDownBase<T> ), new FrameworkPropertyMetadata( default( T ), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnValueChanged, OnCoerceValue, false, UpdateSourceTrigger.LostFocus ) );
I get the following exception: TypeLoadException (GenericArguments [0], 'System.Nullable 1[T]', on 'System.Nullable1 [T]' violates the restriction of the type parameter 'T'.)
When I try to do this (exception occurs when "dynamic" tries to get "ValueProperty"):
var frameWorkElement = e.OriginalSource as FrameworkElement;
while (frameWorkElement != null)
{
if (IsSubclassOfRawGeneric(typeof(UpDownBase<>), frameWorkElement.GetType()))
{
dynamic upDownT = frameWorkElement;
DependencyProperty dp = upDownT.ValueProperty;
if (dp != null)
{
be = frameWorkElement.GetBindingExpression(dp);
if (be != null)
{
be.UpdateSource();
}
}
break;
}
frameWorkElement = VisualTreeHelper.GetParent(frameWorkElement) as FrameworkElement;
}
Why am I getting this exception and how can I get the corresponding dependencyProperty from my object in general (without wiring closets or the like)?
Update
JaredPar, :
private static Type GetGenericBaseTypeOfType(Type generic, Type toCheck)
{
while (toCheck != null && toCheck != typeof(object))
{
var cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;
if (generic == cur)
{
return generic;
}
toCheck = toCheck.BaseType;
}
return null;
}
PropertyInfo .
Type genericbaseType = GetGenericBaseTypeOfType(typeof (UpDownBase<>), frameWorkElement.GetType());
{
if (genericbaseType != null)
{
PropertyInfo pi3 = frameWorkElement.GetType().GetProperty("ValueProperty", BindingFlags.Static | BindingFlags.FlattenHierarchy | BindingFlags.Public);
PropertyInfo pi = genericbaseType.GetProperty("ValueProperty", BindingFlags.Static | BindingFlags.Public);
2
Sacrilege, . , , . , . dependencyProperty, maked GenericType, , , , , . :
Type upDownType = typeof(UpDownBase<>).MakeGenericType(frameWorkElement.GetType().BaseType.GenericTypeArguments[0]);
FieldInfo fi = upDownType.GetField("ValueProperty");
if (fi != null)
{
var dp = fi.GetValue(null) as DependencyProperty;
if (dp != null)
{
be = frameWorkElement.GetBindingExpression(dp);
if (be != null)
{
be.UpdateSource();
}
else
{
be = frameWorkElement.GetBindingExpression(UpDownBase<int>.ValueProperty);
be = frameWorkElement.GetBindingExpression(IntegerUpDown.ValueProperty);
}