我有几个应该显示相同数据的用户控件。每个 UserControl 都有不同的要呈现的数据布局。ContentPresenter 可以通过在我的资源中使用 DataTemplate 并将内容绑定到 StyleViewModel 来绑定到任何一个 UserControl。每个 UserControl 都与 DataTemplate 的 DataType 中定义的 ViewModel 相关联。与任何给定 UserControl 关联的 ViewModel 都继承自 StyleViewModel。UserControls 应该从 SettingsViewModel 获取他们的数据。UserControls 出现在主窗口中。
问题是我不知道如何使 UserControls 可以访问 SettingsViewModel 中的数据。
是否可以将对 SettingsViewModel 的引用传递给使用 ContentPresenter 显示的这些 UserControl 之一的构造函数?
是否有另一种方法可以在不使用 ContentPresenter 的情况下轻松地在不同的数据视图(即我的 UserControls)之间切换?如果是这样,我将如何使用户控件可以访问数据?
以下是我的 SingleLineViewModel.cs 中的代码:
public class SingleLineViewModel : StyleViewModel
{
public SingleLineViewModel() { }
}
其他 ViewModel 类似。它们本质上是从 StyleViewModel 继承的空类,因此我可以在我的 SettingsViewModel 中绑定到 StyleViewModel 类型的 Style 属性。StyleViewModel 也是一个从 ViewModelBase 继承的本质上的空类。
以下是我的 Resources.xaml 中的代码:
<ResourceDictionary <!--other code here-->
xmlns:vm="clr-namespace:MyProject.ViewModel"
<!--other code here-->
<DataTemplate DataType="{x:Type vm:SingleLineViewModel}">
<vw:ucSingleLine/>
</DataTemplate>
<DataTemplate DataType="{x:Type vm:SeparateLinesViewModel}">
<vw:ucSeparateLines/>
</DataTemplate>
<!--other code here-->
</ResourceDictionary>
以下是来自 SettingsViewModel.cs 的代码:
public class SettingsViewModel : ViewModelBase
{
// other code here
private StyleViewModel _style;
public StyleViewModel Style
{
get { return _style; }
set
{
if (value != _style && value != null)
{
_style = value;
OnPropertyChanged("Style");
}
}
}
// other code here
public SettingsViewModel()
{
_style = new SingleLineViewModel();
}
// other code here
}
以下是我的 MainView.xaml 中的代码:
<ContentPresenter Name="MainContent" Content="{Binding SettingsVM.Style}"/>