How to Bind to a Custom Controls Button Visibility from Within Another Control
c#, mvvm, wpf
Solution
You can create `DependencyProperty` in your `UserControl`:
public partial class SomeView : UserControl
{
...
public static DependencyProperty ButtonVisibilityProperty = DependencyProperty.Register("ButtonVisibility", typeof(Visibility), typeof(SomeView));
public Visibility ButtonVisibility
{
get { return (Visibility)GetValue(ButtonVisibilityProperty); }
set { SetValue(ButtonVisibilityProperty, value); }
}
}
bind it to `Button.Visibility`:
<UserControl x:Class="WpfApplication2.SomeView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d">
<Button Visibility="{Binding RelativeSource={RelativeSource AncestorType={x:Type UserControl}}, Path=ButtonVisibility}" Content="My Button"/>
</UserControl>
and then you can control `Visibility` from outside like so:
<local:SomeView ButtonVisibility="Collapsed"/>
and because it's a `DependencyProperty` you can use `Binding` as well
Problem
I have a custom control, which has a button: ``` <UserControl x:Class="Gambit.Views.FileSelectionControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" SnapsToDevicePixels="True" mc:Ignorable="d"> ... <Button Content="Load" Margin="5,5,5,5" Height="22" Width="70" IsDefault="True" IsEnabled="{Binding SelectedFileExists}" AttachedCommand:CommandBehavior.Event="Click" AttachedCommand:CommandBehavior.Command="{Binding CloseDialogCommand}"/> ... </UserControl> ``` I want to include this control, in another control, but I want to set the `Load` buttons visibility at design time in the host control; something like ``` <UserControl x:Class="Gambit.Views.SomeOtherControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" SnapsToDevicePixels="True" mc:Ignorable="d"> ... <GroupBox Header="Select Test Data"> <Views:FileSelectionControl <Here Set the Load Button Visibility>/> </GroupBox> ... </UserControl> ``` where `<Here Set the Load Button Visibility>` shows where i want to set the visibility of the control. How is this done [without breaking the MVVM pattern]? Thanks for your time.