我正在使用模板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); }
}
}
我希望在所有屏幕上保留单选按钮选择。我该怎么做到这一点?
答案 0 :(得分:0)
您必须确保将相同的ViewModel实例用于所有控件实例。 XAML方式总是创建新实例:
<Page.DataContext>
<vm:DetailPageViewModel x:Name="ViewModel" />
</Page.DataContext>
在使用Bootstrapper
方法覆盖的Template10的ResolveForPage
类中,您可以在页面导航后通过自定义逻辑或依赖注入注入ViewModel LINK
答案 1 :(得分:0)
不知道它的改进方式与否,但我通过制作Singletone 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); }
}
我在Constructor中有Instantiated属性:
public ConfigurationViewModel()
{
DeviceManagementViewModel1 = DeviceManagementViewModel._instance;
}
用户控制:
<my:DeviceInfoUserControl OnEndpointTypeChange="{Binding OnEndpointTypeChangeCommand}" Component="{Binding DeviceManagementViewModel1,Mode=TwoWay}"></my:DeviceInfoUserControl>