繁体   English   中英

Tabcontrol MVVM光视图模型绑定

[英]Tabcontrol MVVM light viewmodel binding

我正在使用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

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

<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>

但是我无法将viewmodel绑定到视图。 tabcontrol始终位于inputviewmodel的datacontext中。

任何建议都非常感谢!

不要在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属性指定选项卡项的视图模型属性的名称,以用作选项卡的标题。

通过这种方法,您的设计具有动态性和可扩展性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM