如何从视图调用 ViewModel 中所有属性的 OnChangedProperty?

How to call OnChangedProperty from a View for all Properties in a ViewModel?

我的 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))
    }

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

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

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

然后在你的视图后面的代码中,你需要的只是调用那个方法:

// 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。所以你不需要在后面写任何代码,例如:在你的虚拟机中定义 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>

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