在我的类(class) MainWindow 我有:
public ObservableCollection<ViewModel> VMs ..
MainWindow 是在 XAML 中构造的(它也在类构造函数中创建了一个空 VM):
<Window.Resources>
<c:MainViewModel x:Key="ViewModelsSource"/>
</Window.Resources>
当我单击一个按钮时,我将 ViewModel 对象添加到 ObservableCollection VM,并且 ObservableCollection 的内容显示在 ListBox 中:
<StackPanel DataContext="{Binding Source={StaticResource ViewModelsSource}}">
<ListBox IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding VMs}"
Background="Transparent"
HorizontalContentAlignment="Stretch"
> ...
命令添加的代码是:
void AddListExecute()
{
VMs.Add(new ViewModel());
}
ViewModel 的构造函数是:
public class ViewModel : MainViewModel
{
//Private Members
private ObservableCollection<FeeViewModel> _fees;
//Properties
public ObservableCollection<FeeViewModel> FVMs
{
get
{
return _fees;
}
set
{
_fees = value;
}
}
//Constructor
public ViewModel()
{
this._fees = new ObservableCollection<FeeViewModel>();
}
...
这部分工作正常。每个 ViewModel 对象都包含另一个 ObservableCollection:
public ObservableCollection<FeeViewModel> FVMs ..
我在 XAML 中有一个 tabcontrol,它使用这个 ObservableCollection 来做一些事情:
<TabControl
IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding FVMs, diag:PresentationTraceSources.TraceLevel=High}"
Style="{StaticResource EnabledTabs}" Grid.Column="1" Margin="0,0,10,0">
<TabControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
...
</StackPanel>
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
<DataTemplate>
...
EnabledTabs 是一种使用 FeeViewModel 中的属性的样式:
<Style TargetType="{x:Type TabControl}" x:Key="EnabledTabs">
<Setter Property="IsEnabled" Value="{Binding GotFees}"/>
</Style>
现在我有一个绑定(bind)错误,FVM 为空,窗口中没有显示任何内容。如果我在没有 ViewModel 对象的 ObservableCollection 的情况下恢复到以前的版本,并且将 TabControl 的 DataContext 设置为该单个 ViewModel 一切正常。
如何将 TabControl 的 DataContext 设置为动态创建的 ViewModel 对象?
是否可以在绑定(bind)中执行类似 VM/FVM 的操作?
谢谢
最佳答案
通过将DataContext添加到TabControl解决:
<TabControl
DataContext="{Binding VMs, Source={StaticResource ViewModelsSource}}"
IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding FVMs, diag:PresentationTraceSources.TraceLevel=High}"
Style="{StaticResource EnabledTabs}" Grid.Column="1" Margin="0,0,10,0">
关于c# - 如何在 XAML 中为动态修改的 ObservableCollection 设置 DataContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29588858/