我的解决方案中有两个项目,一个名为UserControls的WPF用户控件库,另一个名为ShopApplication的WPF应用程序。
在UserControls中,我创建了一个名为Product的简单类,该类具有一些属性(字符串名称示例),并由Caliburn Micro MVVM模式设计了用户控件,...我的视图在Views文件夹中是ProductListView.xaml,在ViewModels文件夹中viewmodel名为ProductListViewModel.cs 。ShopApplication始终是MVVM设计的。
我的看法如下所示:
<UserControl x:Class="UserControls.Views.ProductListView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:cal="http://www.caliburnproject.org"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="600"
>
<Grid>
<TextBox Name="SearchingText"/>
<Button x:Name="Search" Content="Search"
cal:Message.Attach="[Click]=[Search()]"/>
</Grid>
</UserControl>
在我的ViewModel中,我有一个名为Search()的方法。
当我通过以下方式将用户控件包括在ShopApplication中时(在应用程序窗口视图中):
<ContentControl DataContext="AreBoughtControl" >
<userControls:ProductListView/>
</ContentControl>
<ContentControl DataContext="WillNeedToBuyControl" >
<userControls:ProductListView/>
</ContentControl>
总是在我单击“搜索”按钮时未处理异常(未找到方法“搜索”的目标。)。但是,当我在应用程序窗口的ViewModel中定义Search方法时,可以并调用方法。
但是我不想在ShopApplication中调用方法,我需要在UserControl中调用方法,该方法在此列表中具有产品列表和搜索名称。
我怎样才能做到这一点 ?寻求答案
我不知道为什么在单击按钮时会引发异常。或者,您可以为按钮单击实现ICommand,而不是直接将搜索方法绑定到按钮单击。这将轻松解决您的问题。由于您的以下MVVM易于实现ICommand。
您可以参考以下链接以获取有关ICommand的详细信息
http://theprofessionalspoint.blogspot.in/2013/04/icommand-interface-and-relaycommand.html
http://www.codeproject.com/Articles/126249/MVVM-Pattern-in-WPF-A-Simple-Tutorial-for-Absolute
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句