【问题标题】:MVVM : Binding external object property [closed]MVVM:绑定外部对象属性
【发布时间】:2017-10-26 06:59:00
【问题描述】:

我有一个相当简单的案例,但我无法找到正确的解决方案。 在我的 MVVM 应用程序上,我希望我的MainView(附加到MainViewModel)通过绑定显示当前用户登录(名称)。

User 类是实现 INPC 的 POCO。 CurrentUser 实例是我的应用程序控制器AppController静态 属性。 LogOn
property 是我想在MainView 中显示的字符串。

这么短的版本:我想在MainView 中绑定AppController.CurrentUser.LogOn

我尝试了几种静态绑定方式(例如在 this article 中),但无法正常工作。

有什么想法可以完成这项工作吗?

谢谢。

编辑:

问题是初始绑定有效,但是当我将另一个 User 对象设置为当前用户时,LogOn 属性不会刷新,即使 AppControl.CurrentUser 属性引发了静态事件 PropertyChanged。

编辑 2

我尝试了@Henk Holterman 解决方案(来自 ViewModel 的回显属性),并对其进行了调试,我发现了诀窍:事实上,问题是一个竞争条件:我的 ViewModel 正在通过 EventAggregator 引发 UserChanged 事件,然后引发 PropertyChanged ,但它太快了,当事件引发时,AppController 上的对象引用没有改变。

非常感谢大家的帮助!

【问题讨论】:

  • LogOn 属性是否通知已更改(即在其设置器中调用 OnNotifyPropertyChanged)?
  • 更重要的是 - AppController.CurrentUser(可能)在加载 MainView 时会发生变化吗?
  • {Binding LogOn, Source={x:Static local:AppController.CurrentUser}} 应该可以工作。
  • 你应该确定的是,AppController.CurrentUser 是在加载视图之前设置的!因为 CurrentUser 是一个静态成员,所以它不能引发 PropertyChanged 事件。
  • 您也可以将该属性回显为MainViewModel.CurrentUser,视图无需知道您的深层架构是什么。

标签: c# wpf mvvm


【解决方案1】:

您的 AppController 类可能如下所示:

public class User
{
    public string LogOn { get; set; }
}

public static class AppController
{
    public static event PropertyChangedEventHandler StaticPropertyChanged;

    private static User currentUser;
    public static User CurrentUser
    {
        get { return currentUser; }
        set
        {
            currentUser = value;
            StaticPropertyChanged?.Invoke(null,
                new PropertyChangedEventArgs(nameof(CurrentUser)));
        }
    }
}

那么 Binding 可能会这样写:

<TextBlock Text="{Binding Path=(local:AppController.CurrentUser).LogOn}"/>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-01
    • 2020-09-30
    • 1970-01-01
    • 2019-01-29
    • 1970-01-01
    • 2011-08-23
    • 2017-11-10
    • 2018-04-06
    相关资源
    最近更新 更多