Search code examples
mvvmuwptemplate10

Maintain User Control State in UWP Application using Template 10


I am creating UWP app using Template 10. I have created user control like this.

enter image description here

 <my:DeviceInfoUserControl  OnEndpointTypeChange="{Binding OnEndpointTypeChangeCommand}" Component="{Binding DeviceManagementViewModel,Mode=TwoWay}"></my:DeviceInfoUserControl>

I have Radio Buttons on User Control. I have added User Control on Multiple screens.

This user control has its own ViewModel as well as Some Dependency Properties as follows:

public class DeviceManagementViewModel : ViewModelBase
{

}
public sealed partial class DeviceInfoUserControl : UserControl
{
    public bool IsToggled = true;
    public DeviceInfoUserControl()
    {
        this.InitializeComponent();
    }

    public static readonly DependencyProperty OnEndpointTypeChangeProperty =
      DependencyProperty.Register(
          "OnEndpointTypeChange",
          typeof(ICommand),
          typeof(DeviceInfoUserControl), new PropertyMetadata(null));

    public ICommand OnEndpointTypeChange
    {
        get { return (ICommand)GetValue(OnEndpointTypeChangeProperty); }
        set { SetValue(OnEndpointTypeChangeProperty, value); }
    }

    public static readonly DependencyProperty ComponentProperty = DependencyProperty.Register("Component", typeof(DeviceManagementViewModel), typeof(DeviceInfoUserControl), new PropertyMetadata(null));

    public DeviceManagementViewModel Component
    {
        get { return (DeviceManagementViewModel)GetValue(ComponentProperty); }
        set { SetValue(ComponentProperty, value); }
    }
}

I want to preserve Radio Button Selection across all screens. How should I achieve this?


Solution

  • Don't know its better way or not but I have achieved this by making Singletone Viewmodel.

     public class DeviceManagementViewModel : ViewModelBase
     {
        public static readonly DeviceManagementViewModel _instance = new DeviceManagementViewModel ();
        private DeviceManagementViewModel ()
        {
    
        }
    /*Properties and Methods */
    
    }
    

    In Parent Screen ViewModel I have created following property

     private DeviceManagementViewModel  _deviceManagementViewModel;
            public DeviceManagementViewModel DeviceManagementViewModel1
            {
                        get { return _deviceManagementViewModel; }
                        set { Set(ref _deviceManagementViewModel, value); }
            }
    

    I have Instantiated property in Constructor:

      public ConfigurationViewModel()
      {
        DeviceManagementViewModel1 = DeviceManagementViewModel._instance;
      }
    

    And on User Control:

    <my:DeviceInfoUserControl  OnEndpointTypeChange="{Binding OnEndpointTypeChangeCommand}"  Component="{Binding DeviceManagementViewModel1,Mode=TwoWay}"></my:DeviceInfoUserControl>