Reputation: 785
I have a WPF user control that has a DependencyProperty called IsMultiSelect. I want to show hide a Button in the UserControl xaml.
<Button Visibility="{Binding IsMultiSelect, Converter=....}" />
This user control has a ViewModel assigned to the DataContext. The above syntax gives me a binding error due to the property not existing in the view model.
How can I fix this error?
Upvotes: 0
Views: 257
Reputation: 8907
You can target the UserControl
in different ways in the binding.
One solution would be to find it by setting a RelativeSource
like this:
<Button Visibility="{Binding IsMultiSelect,
RelativeSource={RelativeSource AncestorType={x:Type UserControl}},
Converter=....}" />
Upvotes: 3
Reputation: 1441
Instead of binding to the property from xaml, the property changed handler for the dependency property should change the button's visibility.
public static readonly DependencyProperty IsMultiSelectProperty = DependencyProperty.Register("IsMultiSelect", typeof(bool), typeof(MyUserControl), new PropertyMetadata(false, OnIsMultiSelectPropertyChanged));
private static void OnIsMultiSelectPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
(sender as MyUserControl).OnIsMultiSelectPropertyChanged(e);
}
private void OnIsMultiSelectPropertyChanged(DependencyPropertyChangedEventArgs e)
{
MyButton.Visibility = (bool)e.NewValue ? Visibility.Visible : Visibility.Collapsed;
}
public bool IsMultiSelect
{
get { return (bool)GetValue(IsMultiSelectProperty); }
set { SetValue(IsMultiSelectProperty, value); }
}
And you can put the converter logic inside OnIsMultiSelectPropertyChanged as well.
Upvotes: -1