0

I have created UserControl that provides few dependency properties. The value of one of them is int. Now the user has provided the null as value and an exception has been thrown:

System.Windows.Data Error: 5 : Value produced by BindingExpression is not valid for target property.; Value='<null>' ...

Which is a valid behaviour (by WPF I believe?). However I want to prepare my UserControl for such incident. I mean, if binding provides invalid value I want to catch this and provide my default value, so no exceptin is thrown.

How to achieve this? I've tried with DependencyPropertyChangedCallback, CoerceValueCallback and ValidateValueCallback callbacks but it seems none of them receive this value.

user2475983
  • 1,916
  • 2
  • 13
  • 20

2 Answers2

1

You can't set an int property to anything else than an int value so your dependency property in the UserControl is actually never being called and there is nothing that the UserControl can do about this as the property never gets set.

It is the responsibility of the consumer of any class including a UserControl to be able to set a property to a value of the property type.

In this case the error occurs when when the WPF runtime is trying to set your int property to a value that doesn't represent a valid integer, such as for example null.

What you could do is to use a ValidationRule to do something before the value conversion occurs and present an error message to the user if the conversion fails:

How do I handle DependencyProperty overflow situations?

Another option may be to change the type of the dependency property to Nullable<int> (int?). Then you will be able to set it to any valid integer value as well as null.

Community
  • 1
  • 1
mm8
  • 163,881
  • 10
  • 57
  • 88
0

In your binding where you bind to that DependencyProperty u can set NullValue and FallbackValue. Somethinkg like.

 <TextBlock  Text="{Binding SomeProperty, FallbackValue='Null not suported', TargetNullValue={x:Null}}"/>
ivica.moke
  • 1,054
  • 2
  • 10
  • 19