2

我有几个应该显示相同数据的用户控件。每个 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}"/>
4

1 回答 1

0

你可能会发现你正在尝试一次做很多事情。考虑如何测试这个场景?或者您将如何在调试器中遍历数据以检查其状态?良好做法建议您的数据与 UI 元素分开。像您尝试使用的 MVVM 模式通常会提供视图模型,以帮助将数据从简单数据转换为 UI 可以使用的表单。考虑到这一点,我建议您尝试开发一个 ViewModel 层,该层在没有 UI 将其保存在一起的情况下呈现所有数据,也就是说,与其尝试将额外的 SettingsViewModel 注入到您的控件中,不如让您的 viewmodel 包含它们需要的所有内容。

看起来你有一个好的开始,你的 SettingsViewModel 让你掌握了一个样式,但你的样式似乎没有任何数据。那么为什么不在构造函数中传递它。

public SettingsViewModel()
{
    _style = new SingleLineViewModel(WhatINeedForStyle);
}
于 2013-01-01T13:25:55.500 回答