WPF - MVVM - 有条件地包含要查看的用户控件
在 WPF 我的 MVVM 应用程序中,我需要创建一个帐户搜索视图,其中有 2 个选项:按帐户 # 进行简单搜索或高级搜索(按姓名、电子邮件等)。
在我的 AccountSearchViewModel 中,我有一个 bool 属性 IsAdvancedMode。
此外,我还为每种模式创建了 2 个 UserControl:SimpleSearchView 和 AdvancedSearchView
现在我需要根据 IsAdvancedMode 属性显示其中之一。
最好的方法是什么?
另外,作为一般解决方案,如果我有枚举的 SearchMode 属性怎么办?在这种情况下,您如何在多个控件之间切换?
In WPF my MVVM application I need to create an account search view with 2 options simple search by account # or Advanced search (by name, email, etc.)
In my AccountSearchViewModel I have a bool property IsAdvancedMode.
Also I have created 2 UserControls for each mode: SimpleSearchView and AdvancedSearchView
Now I need to show either one based on IsAdvancedMode property.
What is the best way to do it?
Also as a general solution what if I have SearchMode property that is enum. How whould you switch between multiple controls in that case?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为您需要使用数据模板,为此,您需要创建三个类:
然后基于类创建数据模板:
I think you need to use Data Templating, to do that you need to create three classes:
and then create Data Template base on Classes:
我将根据需要使用 DataTrigger 交换
ContentControl
的ContentTemplate
。我写了一篇关于在 MVVM 中切换视图的文章这里 如果您感兴趣(包括示例)这里有一些快速测试代码演示它:
I would use a DataTrigger to swap out the
ContentTemplate
of aContentControl
as needed. I wrote an article about switching Views in MVVM here if you're interested (examples included)Here's some quick test code demonstrating it:
我通常将它们都删除,然后使用 BooleanToVisibilityConverter。使用您已设置的最简单的方法。
当
IsAdvancedMode
为true
时,AdvancedSearch 控件将覆盖 SimpleSearch。再次强调,这是最简单的方法,不一定是绝对最好的。I usually drop them both and then use the BooleanToVisibilityConverter. Simplest approach with what you've got set up.
When
IsAdvancedMode
istrue
, the AdvancedSearch control will overlay the SimpleSearch. Again, this is the simplest approach, not necessarily the absolute best.