我已经搜索和尝试了好几天,最后必须在这里问这个问题。 我有一个 Silverlight 5 应用程序,使用 MVVM Light,我希望能够在主视图中动态切换 View 。
为了简单起见,假设我有 2 个按钮。
Button1 将切换到 TestView1。
Button2 将切换到 TestView2。
<Button Content="TestView1" Grid.Column="1" Command="{Binding CallTestView1Command}" HorizontalAlignment="Left" Margin="185,17,0,0" VerticalAlignment="Top" Width="75"/>
<Button Content="TestView2" Grid.Column="1" Command="{Binding CallTestView2Command}" HorizontalAlignment="Left" Margin="280,17,0,0" VerticalAlignment="Top" Width="75"/>
我这样做的方法是将中继命令绑定(bind)到按钮,然后实例化相应 View 的新 View 模型。 即:
private RelayCommand _callTestView1Command;
public RelayCommand CallTestView1Command
{
get
{
return _callTestView1Command ??
(_callTestView1Command = new RelayCommand(() =>
{
CurrentView = ViewModelLocator.NinjectKernel.Get<TestViewModel1>();
}));
}
}
然后将 CurrentViewmodel 设置为新的 View 模型。 在 MainView 中,我已将 CurrentView 绑定(bind)到 ContentControl:
<Border x:Name="displayedView" Grid.Row="2">
<ContentControl Content="{Binding CurrentView}" />
</Border>
这实际上在某种程度上有效,因为 CurrentView 会发生变化,但它不会实际显示 View 的内容,它只是显示实例化的 ViewModel 的命名空间。
到目前为止,我主要使用了从以下来源获取的知识:
http://rachel53461.wordpress.com/2011/05/28/switching-between-viewsusercontrols-using-mvvm/
Loading Views into ContentControl and changing their properties by clicking buttons
但它们没有解决我的问题,或者我不太明白如何实际显示 View 。:-(
有人对如何使用 GalaSoft 的 MVVM Light 在 Silverlight 5 中正确切换 View 有很好的解释吗?
谢谢
最佳答案
您缺少的部分是告诉 WPF 如何渲染 ViewModel 的 DataTemplates
<Window.Resources>
<DataTemplate TargetType="{x:Type local:TestViewModel1}">
<local:TestView1 />
</DataTemplate>
<DataTemplate TargetType="{x:Type local:TestViewModel2}">
<local:TestView2 />
</DataTemplate>
</Window.Resources>
当您在可视化树中插入对象时,例如将 ViewModel
对象放置在 ContentControl.Content
中,默认情况下将使用 TextBlock 绘制该对象
绑定(bind)到对象的 .ToString()
,这就是为什么您只能看到 ViewModel
的 namespace.classname
在您的 ContentControl
通过在您的 Resources
某处定义隐式 DataTemplate
(这是一个仅定义了 TargetType
的 DataTemplate
-没有 x:Key
),您是在告诉 WPF 在尝试绘制指定对象时使用指定的 DataTemplate
来绘制该对象,而不是使用默认的 TextBlock
绑定(bind)到对象的 .ToString()
。
应该注意的是,早期版本的 Silverlight 不支持隐式 DataTemplates
,但 5.0+ 版本支持它们。对于早期版本的 Silverlight,我通常使用 DataTemplateSelector相反。
关于Silverlight 使用 MVVM Light 框架在 View 中切换 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12894124/