c# - 从 UWP 中的 ViewModel B 更新 ViewModel A 的属性

标签 c# mvvm uwp properties

MainPage 显示一个列表和一个按钮。 ListView 的来源是地址(数据绑定(bind))。当用户单击该按钮时,AddAddressPage 将打开。两者都有自己的 ViewModel。在 AddAddressPage 中,用户可以填写公式并单击按钮将新地址添加到列表中。除更新外,一切正常。添加地址后,什么也没有发生,我必须重新启动应用程序才能看到新地址(我也尝试了 ObservableCollection)。我使用了断点,并注意到 Getter 没有被调用,而是 Setter 被调用了两次。

主页面 View 模型:

private List<Address> addresses;

public List<Address> Addresses
{
    get
    {
        return this.addresses;
    }
    set
    {
        this.SetValue(ref this.addresses, value);
    }
}

设定值:
public void SetValue<T>(ref T Backingfield, T value, [CallerMemberName] string propertyName = null)
{
    if (EqualityComparer<T>.Default.Equals(Backingfield, value))
    {
        return;
    }
    else
    {
        Backingfield = value;

        this.OnPropertyChanged(propertyName);
    }
}

地址 View 模型:
// Code to insert new address into SQLite database here...

MainPageViewModel mpvm = new MainPageViewModel();
mpvm.Addresses = SQLite.Select(); // Select returns the database as List

最佳答案

根据您的代码,尽管您在 AddAddressViewModel 中分配了更新的值,但由于您创建的 mpvm 未与 MainPage 中的 ListView 绑定(bind),因此它会更改但不会影响 ListView。所以你可以订阅关闭新窗口的事件,当您关闭 AddAddressPage 时,将触发该事件。然后您可以返回主视图并将新数据分配给它的 Addresses 属性。例如:

MainPageViewModel.cs:

private async void ToAddAddress()
{
    CoreApplicationView newView = CoreApplication.CreateNewView();
    var newViewId = 0;

    await newView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
    {
        Frame frame = new Frame();
        frame.Navigate(typeof(AddAddressPage), this.addresses);
        Window.Current.Content = frame;

        // You have to activate the window in order to show it later.
        Window.Current.Activate();
        Window.Current.Closed += Current_Closed;
        newViewId = ApplicationView.GetForCurrentView().Id;
    });

    bool viewShown = await ApplicationViewSwitcher.TryShowAsStandaloneAsync(newViewId);            
}

private async void Current_Closed(object sender, CoreWindowEventArgs e)
{
    await CoreApplication.MainView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
    {
        this.Addresses = SQLite.Select();
    });
}

关于c# - 从 UWP 中的 ViewModel B 更新 ViewModel A 的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61059106/

相关文章:

c# - 将动态创建的组合框绑定(bind)到 View 模型上的属性

uwp - 模板化 ItemsControl 的弹出窗口中的 ItemsPresenter 在第一次显示时仅显示 1 个项目,在第二次显示时加载所有内容

c# - UWP 全屏 : How to hide taskbar on hover?

wpf - 使用相同的 DataContext 设置 DataGrid 和 ContextMenu

extjs 数据绑定(bind) ViewModel 和网格不起作用

c++ - co_await 不工作

c# - Startup.cs中的ASP.NET Core访问服务的ConfigureServices方法

c# - XNA for WP7 和多点触控每帧更新

c# - 用集合EntityFramework连接表

c# - ICQ UIN 的正则表达式