Search code examples
wpfdata-bindingcustom-controlsvisibilitycontentcontrol

Binding Property to Two Different Controls


I have a WPF form with a content control and a custom control. The content control swaps in views based on a radio button selection. Once the user takes an action on the view, I set the nocustomer on the parent viewmodel (the WPF form containing the two controls) to false. When this occurs, the visibility of content control correctly disappears. Unfortunately, the visibility of the custom control remains unchanged (it should have also disappeared). I'm actually perplexed because in my mind they have the exact same implementation and therefore should behave the same.

<ContentControl x:Name="ViewSwap" Content="{Binding SearchingViewModel}" 
Visibility="{Binding NoCustomer, Converter={StaticResource 
BooleanToVisibilityConverter}, Mode=OneWay}">
    <ContentControl.Style>
        <Style TargetType="{x:Type ContentControl}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding ElementName=SearchOptions, Path=IsSelected}" Value="0">
                    <Setter Property="ContentTemplate" Value="{StaticResource AddressTemplate}" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </ContentControl.Style>
</ContentControl>

<views:CTACallSubmit x:Name="CallSubmit" 
Visibility="{Binding NoCustomer, Converter={StaticResource 
BooleanToVisibilityConverter}, Mode=OneWay}"/>

Update:

MainWindow's DataContext

public partial class CTALight : Window
{
    public CTALight()
    {
        InitializeComponent();

        this.DataContext = CTALightViewModel.GetInstance();
    }
}

MainViewModel

 public class CTALightViewModel : ObservableObject
 {
    public static CTALightViewModel _mainViewModel;

    public static CTALightViewModel GetInstance()
    {
        if (_mainViewModel == null)
            _mainViewModel = new CTALightViewModel();          

        return _mainViewModel;
    }

    private CTALightViewModel()
    {
    }

}

CTACallSubmit DataContext

<UserControl.DataContext>
    <viewmodel:CTACallSubmitViewModel />
</UserControl.DataContext>

Solution

  • The following creates a new instance of CTACallSubmitViewModel and sets the DataContext of the UserControl to this one.

    <UserControl.DataContext>
        <viewmodel:CTACallSubmitViewModel />
    </UserControl.DataContext>
    

    This means that the binding to the NoCustomer property of the other view model won't work unless you specify a source of the binding:

    <views:CTACallSubmit x:Name="CallSubmit" 
            Visibility="{Binding DataContext.NoCustomer, 
            RelativeSource={RelativeSource AncestorType=Window}, 
            Converter={StaticResource BooleanToVisibilityConverter}, Mode=OneWay}"/>
    

    Setting the DataContext of a UserControl like this is usually a bad idea as it breaks the inheritance of the parent's DataContext.