【问题标题】:How to call OnChangedProperty from a View for all Properties in a ViewModel?如何从 View 中为 ViewModel 中的所有属性调用 OnChange 属性?
【发布时间】:2018-05-02 07:17:57
【问题描述】:

我的 Page1.xaml.cs(代码隐藏)中有一个需要更改 ViewModel 中所有属性的事件。

这里是一个例子:(Page1.xaml.cs)

public Page1()
{        
    InitializeComponent();

    example.Event += example_Event;
}

private void example_Event(...)
{ 
    // here I want to change all Properties in my ViewModel
}

我怎样才能做到这一点?

编辑

我有一个显示 .ppt 的 WebBrowser-Control。我想在触发此事件时更新 ViewModel 中的所有属性:

xaml.cs:

private void powerPointBrowser1_LoadCompleted(object sender, NavigationEventArgs e)
    {
        //...
        oPPApplication.SlideShowNextSlide += ppApp_SlideShowNextSlide; //Event that gets triggered when i change the Slide in my WebBrowser-Control

    }

private void ppApp_SlideShowNextSlide(PPt.SlideShowWindow Wn)
    {
          // here i dont know how to get access to my Properties in my VM (i want to call OnChangedProperty(//for all properties in my VM))
    }

【问题讨论】:

  • 使用 null 或空属性名称触发视图模型的 PropertyChanged 事件。
  • 是的,我知道我必须使用 string.empty ^^ 但我不知道如何在我的代码隐藏中触发 OnPropertyChanged 以获取我的 VM 中的属性。
  • 我们也不知道,因为您没有向我们展示您的视图模型的相关部分。我会说,向调用 OnPropertyChanged 的​​视图模型添加一个公共方法。
  • 提升datacontextchanged怎么样? msdn.microsoft.com/en-us/library/…
  • 对我来说似乎是XY problem。您实际上想要达到什么目标?

标签: c# wpf inotifypropertychanged


【解决方案1】:

通常情况下,View(包括后面的代码)没有责任通知 ViewModel 的属性被更新,它应该是相反的。但是,我看到在您的情况下,您希望在处理某些事件时做某些事情(在这种情况下,检索每个属性的最新值),所以这里是:您需要的一些解决方案。

在您的 VM 中,定义一个方法,将 PropertyChanged 触发到所有属性:

public void UpdateAllProperties()
{
    // Call OnPropertyChanged to all of your properties
    OnPropertyChanged(); // etc. 
}

那么在你的 View 后面的代码中,你只需要调用那个方法:

// every View has a ViewModel that is bound to be View's DataContext. So cast it, and call the public method we defined earlier.
((MyViewModel)DataContext).UpdateAllProperties();

不幸的是,这种方法对于 MVVM 风格来说不是很优雅。我建议您将此方法/事件处理程序设置为可绑定ICommand。因此,您无需在后面编写任何代码,例如:在您的 VM 中定义 ICommand

public ICommand UpdateAllPropertiesCommand {get; private set;}
   = new Prism.Commands.DelegateCommand(UpdateAllProperties);
// You can switch the UpdateAllProperties method to private instead.
// Then remove any code behinds you had.

然后,在您的视图 (xaml) 中,您可以将 ICommand 绑定到某个控件的事件触发器。

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"

<!--In one of the controls-->
<i:Interaction.Triggers>
   <i:EventTrigger EventName="Loaded">
      <i:InvokeCommandAction Command="{Binding UpdateAllPropertiesCommand , Mode=OneTime}"/>
   </i:EventTrigger>
</i:Interaction.Triggers>

这里在处理加载的事件时会自动调用该命令。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-14
    • 1970-01-01
    • 2013-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多