我的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
}我怎样才能做到这一点?
编辑
我有一个WebBrowser控件,显示一个.ppt。当触发此事件时,我希望更新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))
}发布于 2018-05-07 01:58:35
通常,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风格来说,这种方法并不是很优雅。我建议您将此方法/事件处理程序设置为Bindable 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>在这里,在处理加载事件时将自动调用该命令。
https://stackoverflow.com/questions/50129073
复制相似问题