Search code examples
c#wpfmvvmuser-controlsmvvm-foundation

Making a Generic UserControl which can be accessed by other view


I have UserControl A given below with two Radio Buttons. This UserControl view has its ViewModel.

Question: I again have two Views Create and Edit. I want to use the above mentioned UserControl within Create/Edit with requirement that i can make the radiobuttons or any of the elements in UserControl to be Visible or Hidden based on the requirement in Create/Edit View.

Eg: Create May not require Radio button 1 and 2.So only Rectangle must be displayed. Whatever input i give in the list or textbox must be updated in UserControl's ViewModel and the search result after clicking on button must be sent to Create/Edit accordingly. Note:Create/Edit have their own ViewModels.Please suggest which approach is best considering MVVM

The Control has to be placed in the grayed out area as shown in rectangle for Create/Edit View

Search Control

Create,Edit


Solution

  • You can create DependancyProperty inside your UserControl like

    public static readonly DependencyProperty RadioButtonVisibilityProperty= 
     DependencyProperty.Register( "RadioButtonVisibility", typeof(Visibility),
     typeof(MyUserControl));
    
    
    public Visibility RadioButtonVisibility 
    {
        get { return (Visibility)GetValue(RadioButtonVisibilityProperty); }
        set { SetValue(RadioButtonVisibilityProperty, value); }
    }
    

    and inside your UserControl's xaml Set the radiobutton's visibility like

    <RadioButton Visibility="{Binding Parent.RadioButtonVisibility,ElementName=LayoutRoot}"/>
    

    and in your main View(Create/Edit) do like this

    <MyUserControl x:Name="Edit" RadioButtonVisibility="Visible"/> 
    

    or

    <MyUserControl x:Name="Create" RadioButtonVisibility="Hidden"/>
    

    And dont forget to give your UserControl's parent Grid the name "LayoutRoot"

    like

    <Grid x:Name="LayoutRoot"/>