Reputation: 883
I have a Camera object which has properties like Name, SensorWidth, SensorHeight etc. I would like to bind these properties to UI, but Camera is null at the time application starts (user can select any camera). Only when camera is opened, Camera object is initialized (and loads all its properties).
Is there a way to setup data binding in XAML so it starts to work when object is initialized?
I can do this easily in C# - setup data binding after camera is opened but this would had to be done in View code behind, which is probably bad for MVVM pattern I am using, since the button for opening camera is using Command interface to communicate with ViewModel.
What is the way to correctly approach this?
Upvotes: 1
Views: 1708
Reputation: 25623
Is there a way to setup data binding in XAML so it starts to work when object is initialized?
Bindings are designed to handle null values gracefully. There should be no problem if your Camera
object is null at startup. WPF expects that the binding source might be null, and that any values along the property path might be null.
That said, it is useful to understand when a Binding
produces a value successfully:
If (1) and (2) fail to produce a valid value, the binding will produce the default value of the target property. If you want to specify an alterate value to use in this situation, you can provide a FallbackValue
on your binding.
In your case, if you have {Binding Camera.Name}
, and Camera
is null, the binding will fail to produce a value. If you changed the binding to {Binding Camera.Name, FallbackValue='n/a'}
, then it produce the string n/a
when Camera
is null.
TargetNullValue
lets you specify an alternate value in cases where the binding does produce a valid value, but that value is null. For example, if Camera
itself is non-null, but its Name
is null, then {Binding Camera.Name, TargetNullValue='(no name)'}
will produce the string (no name)
.
Upvotes: 4