【问题标题】:Tabcontrol MVVM light viewmodel bindingTabcontrol MVVM 灯光视图模型绑定
【发布时间】:2018-11-25 08:19:16
【问题描述】:

我正在使用 Galasoft MVVM Light Framework。

我想要实现的是:

我目前得到的是:

我的所有视图模型都静态声明为 MainViewModel.cs 中的实例字段,因此它们在窗口之间切换时保持状态:

    #region Viewmodels init.
    readonly static InputViewModel _inputViewModel = new InputViewModel();
    [...]
    readonly static LicensesViewModel _licensesViewModel = new LicensesViewModel();
    readonly static PricesViewModel _pricesViewModel = new PricesViewModel();
    #endregion

在我的输入用户控件中,我正在显示一个选项卡控件。 在每个 tabitem 中,我将一个新的用户控件绑定为视图

<UserControl>
        <DockPanel>
            <TabControl>
                <TabItem Header="Prices">
                    <local:PricesControl DataContext="{x:Type viewModels:PricesViewModel}" />
                </TabItem>
                <TabItem Header="Licenses">
                    <local:LicenseControl DataContext="{x:Type viewModels:LicensesViewModel}" />
                </TabItem>
            </TabControl>
        </DockPanel>
    </UserControl>

但是,我无法将视图模型绑定到视图。 tabcontrol 总是在 inputviewmodel 的数据上下文中。

非常感谢任何建议!

【问题讨论】:

  • 将 TabControl 绑定到包含视图模型的集合并使用数据模板来显示控件。如果您需要任何进一步的帮助,您需要提供类的定义。例如,您为什么要在 MainViewModel 中而不是在 InputViewModel 中实例化 LicenceViewModel?

标签: c# wpf mvvm mvvm-light


【解决方案1】:

不要在 MainViewModel 中使用 static 字段,这是一个糟糕的设计决策,会使您的代码无法测试。

改为使用 WPF 强大的数据模板机制。

class MainViewModel : INotifyPropertyChanged
{
    // Note: this is just a sample.
    // You might want to inject the instances via DI
    public IEnumerable<INotifyPropertyChanged> TabItems { get; } =
        new[] { new PricesViewModel(), new LicensesViewModel() };
}

为您的视图模型使用数据模板:

<TabControl ItemsSource="{Binding TabItems}" DisplayMemberPath="PropertyNameForTabHeader">
    <TabControl.Resources>
        <DataTemplate DataType="{x:Type viewModels:PricesViewModel}">
            <local:PricesControl/>
        </DataTemplate>
        <DataTemplate DataType="{x:Type viewModels:LicensesViewModel}">
            <local:LicenseControl/>
        </DataTemplate>
    </TabControl.Resources>
</TabControl>

DisplayMemberPath 属性指定选项卡项的视图模型属性的名称以用作选项卡的标题。

使用这种方法,您的设计是动态且可扩展的。

【讨论】:

  • 绝对是这样。
  • 非常感谢您花时间回答。它完美地工作+我摆脱了静态视图模型,所以奖励:-)
猜你喜欢
  • 2018-10-25
  • 1970-01-01
  • 2012-07-22
  • 1970-01-01
  • 2012-07-31
  • 1970-01-01
  • 2011-10-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多