我正在使用 MVVM 开发 Windows 8 Store 应用程序。
我的要求是创建一个动态调查页面,根据问题类型(多选、单选、文本框或评分按钮),我必须向用户显示带有值的答案。
我的问题是:
如何在 View 中显示动态控件。
我应该在 View Model cs 文件或 View 的 Cs 文件中创建动态控件。
请给我一些建议。
谢谢阅读
问候
美居
最佳答案
1)例如,我像这样使用 ViewModel:
public enum AnswerType {OneAnswer, MultipleAnswers}
public class QuestionViewModel : ViewModel
{
public AnswerType type;
public string[] Answers;
}
2) View 职责——表示来自 ViewModel 的数据:
我在 XAML 中的空 View :
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
x:Class="AnswerView.cs"
xmlns:local="clr-namespace:sdkControlTiltEffect"
mc:Ignorable="d"
d:DesignHeight="173" d:DesignWidth="173">
<Grid x:Name="LayoutRoot">
</Grid>
</UserControl>
我将 ViewModel 作为构造函数参数注入(inject)到 View 中。您可以改用 DataContext 。
我的动态 View 背景类:
public class AnswerView : UserControl
{
public AnswerView(QuestionViewModel q)
{
switch(q.Type)
{
case AnswerType.OneAnswer:
//Put log for jne answer view generation
break;
case AnswerType.MultipleAnswers:
//Put logic for multiple answers View generation
break;
default:
}
}
}
您永远不应该在 ViewModel 中创建 View 元素。它从根本上破坏了 MVVM。 ViewModel 必须独立于 View。
我认为这应该会有所帮助:
MVVM and dynamic generation of controls
关于c# - 在 View 中为 MVVM windows 8 动态生成控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20064821/