【发布时间】:2014-08-16 10:49:16
【问题描述】:
编辑: 问题是我的视图模型不是公开的,所以没有找到绑定。出于某种原因,它们需要在 Silverlight 中公开,即使私有视图模型适用于 WPF。更多详细信息请参见下面的回答。
我正在尝试在 Silverlight 中实现一个 MVVM WPF 应用程序,但我之前从未使用过 Silverlight。我正在努力让绑定的内容显示出来。我几乎完全按照我使用 WPF 的方式实现它,除了 Main 位是 UserControl,而不是 Window,应用程序由网站托管,我必须删除 DataTemplate DataType 中的 x:Type
我的 Website-to-MainPage 工作正常,因为我可以在该页面中显示一个文本框或其他内容,但只是不显示绑定。有什么建议吗?
我的 MainPage.xaml.cs:
public partial class MainPage : UserControl
{
private MainPageViewModel _viewModel;
public MainPage()
{
InitializeComponent();
_viewModel = new MainPageViewModel();
this.DataContext = _viewModel;
}
}
我的 MainPage.xaml:
<UserControl x:Class="TransformationServices.Silverlight.MainPage"
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"
mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="400"
xmlns:view="clr-namespace:TransformationServices.Silverlight.View"
xmlns:viewModel="clr-namespace:TransformationServices.Silverlight.ViewModel"
xmlns:local="clr-namespace:TransformationServices.Silverlight"
Background="#FF2D2D30">
<UserControl.Resources>
<local:ViewConverter x:Key="viewConverter"/>
<DataTemplate DataType="viewModel:InputSelectViewModel">
<TextBlock Text="Hello World!"/>
<!-- This textblock is just for testing. It doesn't work, and neither does the following line-->
<view:InputSelect/>
</DataTemplate>
</UserControl.Resources>
<ContentControl Content="{Binding CurrentView}" />
</UserControl>
我的 MainPageViewModel.cs
class MainPageViewModel : ViewModelBase, INotifyPropertyChanged
{
private ViewModelBase _currentView;
private List<ViewModelBase> _viewModels;
private int _viewIndex;
public ViewModelBase CurrentView
{
get { return _currentView; }
set
{
if (value != _currentView)
{
_currentView = value;
OnPropertyChanged("CurrentView");
}
}
}
public MainPageViewModel()
{
_viewModels = new List<ViewModelBase>();
// Add view models here
_viewModels.Add(new InputSelectViewModel());
_viewIndex = 0;
CurrentView = _viewModels[_viewIndex];
}
}
【问题讨论】:
-
看起来有效,应该显示隐式DataTemplate。那么有什么问题呢?确保您使用 Silverlight 5 并且您的浏览器使用 SL5 运行时,因为自 SL5 起才支持隐式 DataTemplates。您可以尝试解决问题的另一件事:明确设置模板,看看它是否显示。喜欢...
标签: c# wpf silverlight xaml mvvm