我正在使用MVVM模式(无框架,只是原始的MVVM)开发Windows应用商店应用程序。使用MVVM的Windows商店应用程序中的事件处理
我有一个用户控件DropboxFileplanUserControl.xaml
它有一个关联的视图模型DropboxFileplanViewModel.cs
。 DropboxFileplanUserControl
嵌入MainPage.xaml
,MainPage.xaml
有一个关联的视图模型,MainPageViewModel.cs
。
我的问题是我如何定义和引发DropboxFileplanViewModel.cs
中的事件并在MainPageViewModel.cs
中处理?假设要提出的事件称为ImageLoaded
。
编辑:我已经添加了以下具体的代码片段...
DropboxFileplanUserControl.xaml
<UserControl
x:Class="PhotoBox.Controls.DropboxFileplanUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:PhotoBox.Controls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:viewModels="using:PhotoBox.ViewModels"
xmlns:triggers="using:WinRT.Triggers"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="200">
<UserControl.DataContext>
<viewModels:DropboxFileplanViewModel />
</UserControl.DataContext>
<Grid>
<ListBox>
<!--
...
...
Here I define a ListBox and use interaction triggers to bind the SelectionChanged event to FileplanSelectionChangedCommand on the ViewModel -->
<triggers:Interactions.Triggers>
<triggers:EventTrigger EventName="SelectionChanged">
<triggers:InvokeCommandAction Command="{Binding FileplanSelectionChangedCommand}" PassEventArgsToCommand="True" />
</triggers:EventTrigger>
</triggers:Interactions.Triggers>
</ListBox>
</Grid>
DropboxFileplanViewModel.xaml注:我已经剥离了很多来自此片段的代码
public class DropboxFileplanViewModel : ViewModel
{
public DelegateCommand FileplanSelectionChangedCommand { get; set; }
public DropboxFileplanViewModel()
{
FileplanSelectionChangedCommand = new DelegateCommand(FileplanSelectionChanged);
}
private void FileplanSelectionChanged(object parameter)
{
var args = (SelectionChangedEventArgs) parameter;
// Some other stuff is done here but ultimately,
// GetImageFile is called
}
private async void GetImageFile(MetaData file)
{
// Stuff is done here to get the image
// ******************************
// Here I want to raise the event
// ******************************
}
}
DropboxFileplanUserControl
嵌入MainPage.xaml
如下...
MainPage.xaml中
<controls:DropboxFileplanUserControl
Grid.Row="0"
DataContext="{Binding FileplanControl}"
Visibility="{Binding IsOpen, Converter={StaticResource BooleanToVisibilityConverter}}"
IsEnabled="{Binding IsOpen}"
<!-- *** Here I need to access the ImageLoaded event and bind it to a command in MainPageViewModel.cs *** -->
/>
因此,要总结,我需要声明和DropboxFileplanViewModel.cs
引发一个事件,并在访问此事件MainPage.xaml
所以我可以在MainPageViewModel.cs
中处理它。我知道如何将MainPage.xaml
中的事件绑定到MainPageViewModel
中的命令,我只需要知道如何执行第一个位,即在DropboxFileplanViewModel.cs
中声明并引发事件并在MainPage.xaml
中访问它。
您是否使用基类来存储ViewModelLocator(mvvm light)等视图模型?你可以把一些代码放到你的xaml和viewmodels中吗? – SWilko
我的viewmodels的继承层次结构是'ViewModel:BindableBase:INotifyPropertyChanged'。我尽量保持原始问题的类名尽可能通用,但我会用实际的代码片段编辑帖子。 –
感谢您的代码。一个简单的方法就是使用mvvmlight中的Messenger类,但是我认为在你不使用框架之前先检查答案。 – SWilko