在我的窗口资源中,我有一个用于我的viewmodel的数据窗口和一个静态mainviewmodel
<Window.Resources>
<DataTemplate DataType="{x:Type SharedViewModels:DatabaseViewModel}">
<SharedViews:DatabaseView/>
</DataTemplate>
<LocalViewModels:SharedSettingsViewModel x:Key="SharedSettingsViewModel"/>
</Window.Resources>
DatabaseViewModel
是我的静态SharedSettingsViewModel
中的一个实例
我有这个标签控件
<TabControl DataContext="{Binding Source={StaticResource SharedSettingsViewModel}}" ItemsSource="{Binding SharedSettingsViewModelsTabList}">
<TabControl.ItemTemplate>
<DataTemplate>
<ContentPresenter Content="{Binding Content}"/>
</DataTemplate>
</TabControl.ItemTemplate>
</TabControl>
我将项目添加到我的TabControl项目中,如此
SharedSettingsViewModelTabList.Add(new Shared.Models.TabItem() { Header = "Sql Databases", Content = DatabaseViewModel });
如何将DatabaseView
的datacontext设置为DatabaseViewModel
内的SharedSettingsViewModel
实例?
在我看来DatabaseView XAML是我试过的用户控件
DataContext="{Binding DatabaseViewModel}"
但这似乎不起作用
这是我的TabItem模型
public class TabItem : MVVM.ObservableObject
{
public string Header { get; set; }
public MVVM.ObservableObject Content { get; set; }
}
我的DatabaseViewModel,它将被定义为SharedSettingsViewModel中的一个属性
private ObservableCollection<Models.Database> databases;
public ObservableCollection<Models.Database> Databases
{
get
{
if (databases == null)
{
databases = new ObservableCollection<Models.Database>();
databases.Add(new Models.Database() { Displayname = "new" });
}
return databases;
}
set
{
SetField(ref databases, value, "Databases");
}
}
这是我的SharedSettingsViewModel,其中包含标签项集合
public class SharedSettingsViewModel : MVVM.ObservableObject
{
private ObservableCollection<Shared.Models.TabItem> SharedSettingsViewModelTabList;
public ObservableCollection<Shared.Models.TabItem> SharedSettingsViewModelTabList
{
get
{
if (sharedSettingsViewModelTabList == null)
{
sharedSettingsViewModelTabList = new ObservableCollection<Shared.Models.TabItem>();
}
return sharedSettingsViewModelTabList;
}
}
//my DatabaseViewModel property..as a child view model
private Shared.ViewModels.DatabaseViewModel databaseViewModel;
public Shared.ViewModels.DatabaseViewModel DatabaseViewModel
{
get
{
if (databaseViewModel == null)
{
databaseViewModel = new Shared.ViewModels.DatabaseViewModel();
}
return databaseViewModel;
}
set
{
SetField(ref databaseViewModel, value, "DatabaseViewModel");
}
}
}
答案 0 :(得分:1)
您必须更新以下代码,DatabaseViewModel
将成为DataContext
的{{1}} DatabaseView
DataTemplate
Content
在ContentPresenter
ContentTemplate
中TabControl
<TabControlDataContext="{Binding Source={StaticResource SharedSettingsViewModel}}" ItemsSource="{Binding SharedSettingsViewModelsTabList}">
<TabControl.ContentTemplate>
<DataTemplate>
<ContentPresenter Content="{Binding Content}"/>
</DataTemplate>
</TabControl.ContentTemplate>
<TabControl.ItemContainerStyle>
<Style TargetType="TabItem">
<Setter Property="Header" Value="{Binding Header}"/>
</Style>
</TabControl.ItemContainerStyle>
</TabControl>