Reputation: 381
I have some classes. Some of them has Color Property, but one does not. I'm using same ListBox User Control for them. I want to hide ColorPicker for those classes that have no such property. I know, I can do a workaround and hide it if DataContext is of certain type, but I want to know if there is a way to check if the binding target isn't just null at a moment, but doesn't exist at all.
I used the proposed converter (returning true/false) with no result, but @mm8 proposal to set FallbackValue to false worked well.
Upvotes: 2
Views: 649
Reputation: 169330
You could specify a FallbackValue
for a specific binding that the target property will be set the when the source property is not found: https://msdn.microsoft.com/en-us/library/system.windows.data.bindingbase.fallbackvalue(v=vs.110).aspx
Upvotes: 2
Reputation: 27605
Use a ValueConverter for the binding, and in the Convert method, check for UnsetValue
:
<FrameworkElement Property="{Binding SomeProperty, Converter={StaticResource BindingExists}/>
and
public class BindingExists : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == DependencyProperty.UnsetValue)
{
// perhaps do something
return Binding.DoNothing;
}
else if (value == null)
{
// perhaps do something else
}
return value
}
// ...
You can then use DataTriggers
to display different templates or whatever, in case of null vs. non-existent value.
Upvotes: 1