문제

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

도움이 되었습니까?

해결책

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"/>

다른 팁

It might be a good idea to have the UserControl be driven by some abstract BaseViewModel. Then you create two sub-classes EditViewModel and CreateViewModel which you then use based on the context.

Quick crude example for the radio buttons:

public abstract class BaseViewModel
{
  public bool ShowRadioButtons { get; protected set; }
}

public class EditViewModel : BaseViewModel
{
  public EditViewModel()
  {
    ShowRadioButtons = true;
  }
}

public class CreateViewModel : BaseViewModel
{
  public CreateViewModel()
  {
    ShowRadioButtons = false;
  }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top