首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从视图中调用OnChangedProperty用于ViewModel中的所有属性?

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

Stack Overflow用户
提问于 2018-05-02 07:17:57
回答 1查看 348关注 0票数 0

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

下面是一个示例:(Page1.xaml.cs)

代码语言:javascript
复制
public Page1()
{        
    InitializeComponent();

    example.Event += example_Event;
}

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

我怎样才能做到这一点?

编辑

我有一个WebBrowser控件,显示一个.ppt。当触发此事件时,我希望更新ViewModel中的所有属性:

xaml.cs:

代码语言:javascript
复制
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))
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-05-07 01:58:35

通常,View (包括后面的代码)没有责任通知ViewModel的属性被更新,它应该是相反的。但是,我看到在您的示例中,您希望在处理某些事件时执行某些操作(在本例中,检索每个属性的最新值),因此您需要一些解决方案。

在VM中,定义一个向所有属性激发PropertyChanged的方法:

代码语言:javascript
复制
public void UpdateAllProperties()
{
    // Call OnPropertyChanged to all of your properties
    OnPropertyChanged(); // etc. 
}

然后,在视图后面的代码中,只需调用该方法:

代码语言:javascript
复制
// 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风格来说,这种方法并不是很优雅。我建议您将此方法/事件处理程序设置为Bindable ICommand。因此,您不需要在后面编写任何代码,以便在VM中定义ICommand

代码语言:javascript
复制
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绑定到某些控件的事件触发器。

代码语言:javascript
复制
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>

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50129073

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档