使用模板 10 在 UWP 应用程序中维护用户控件状态

Maintain User Control State in UWP Application using Template 10

我正在使用模板 10 创建 UWP 应用程序。我已经创建了这样的用户控件。

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

我在用户控件上有单选按钮。我在多个屏幕上添加了用户控制。

此用户控件有自己的 ViewModel 以及一些依赖属性,如下所示:

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); }
    }
}

我想在所有屏幕上保留单选按钮选择。我该如何实现?

您必须确保相同的 ViewModel 实例用于所有控件实例。 XAML 方法总是创建新实例:

<Page.DataContext>
    <vm:DetailPageViewModel x:Name="ViewModel" />
</Page.DataContext>

在 Template10 的 Bootstrapper class 中使用 ResolveForPage 方法覆盖,您可以通过自定义逻辑或依赖注入 LINK 在页面导航后注入 ViewModel

不知道有没有更好的方法,但我已经通过制作 Singleton Viewmodel 实现了这一点。

 public class DeviceManagementViewModel : ViewModelBase
 {
    public static readonly DeviceManagementViewModel _instance = new DeviceManagementViewModel ();
    private DeviceManagementViewModel ()
    {

    }
/*Properties and Methods */

}

在父屏幕 ViewModel 中,我创建了以下 属性

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

我在构造函数中实例化了属性:

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

在用户控件上:

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