gpt4 book ai didi

c# - Tabcontrol MVVM light View 模型绑定(bind)

转载 作者:太空宇宙 更新时间:2023-11-03 22:43:57 25 4
gpt4 key购买 nike

我正在使用 Galasoft MVVM Light Framework。

我想实现的是: enter image description here

我目前得到的是这样的: enter image description here

我的所有 View 模型都在我的 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 中,我将一个新的用户控件绑定(bind)为 View

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

但是我无法将 View 模型绑定(bind)到 View 。选项卡控件始终位于输入 View 模型的数据上下文中。

非常感谢任何建议!

最佳答案

不要在 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() };
}

为您的 View 模型使用数据模板:

<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 属性指定要用作选项卡标题的选项卡项的 View 模型属性的名称。

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

关于c# - Tabcontrol MVVM light View 模型绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50876382/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com