ContentDialog 内元素的绑定状态有问题

问题描述 投票:0回答:1

我目前正在尝试恢复别人的项目。 在原始项目中,有一个使用 ContentDialog 的“MainMenu”页面。

我已在该菜单中添加了一个复选框,并尝试通过 x:Bind 绑定到它。

MenuViewModel 看起来像这样

namespace NScumm.MonoGame.ViewModels
{
    public class MenuViewModel : ViewModel, IMenuViewModel
    {
        private bool _showFPS;

        public bool ShowFPS
        {
            get { return _showFPS; }
            set 
            { 
                RaiseAndSetIfChanged(ref _showFPS, value);
            }
        }
    }
}

有一个更通用的视图模型实现了 OnPropertyChanged

using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace NScumm.MonoGame.ViewModels
{
    public abstract class ViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            var eh = PropertyChanged;
            eh?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        public virtual void RaiseAndSetIfChanged<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
        {
            if (!EqualityComparer<T>.Default.Equals(field, value))
            {
                field = value;
                OnPropertyChanged(propertyName);
            }
        }
    }
}

在代码隐藏中我初始化了 MenuViewModel

public MainMenuPage()
    {
        InitializeComponent();

        Vm = new MenuViewModel();
        DataContext = Vm;
    }

    public MenuViewModel Vm { get; set; }

最后,在 XAML 中添加复选框

<CheckBox x:Name="ShowFPScheckBox" Margin="5" IsChecked="{x:Bind Vm.ShowFPS, Mode=TwoWay}">FPS Counter</CheckBox>

每当我关闭并重新打开菜单时,该复选框就会恢复为默认值 false。

我是否做错了什么,或者 ContentDialog 是否存在不保留其状态的已知问题?

c# xaml uwp xbox
1个回答
0
投票

每当我关闭并重新打开菜单时,复选框就会恢复到原来的状态 默认值为 false。

 Vm = new MenuViewModel();
 DataContext = Vm;

每次打开 ContentDialog 时,都会创建一个新的 Vm,其默认布尔值 false。

如果您希望 ContentDialog 记住您的选择,建议您使用数据库本地资源来保存用户的选择并在每次打开时读取它。

private void ContentDialog_Closing(ContentDialog sender, ContentDialogClosingEventArgs args)
{
    bool isChecked = ShowFPScheckBox.IsChecked ?? false;
    ApplicationData.Current.LocalSettings.Values["FpsCheckBoxState"] = isChecked;
  
}

private void ContentDialog_Loaded(object sender, RoutedEventArgs e)
{
    if (ApplicationData.Current.LocalSettings.Values["FpsCheckBoxState"]!=null)
    {
        ShowFPScheckBox.IsChecked = (bool)ApplicationData.Current.LocalSettings.Values["FpsCheckBoxState"];
    }
    else
    {
        ShowFPScheckBox.IsChecked = false;
    }

}
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.