如何将可观察集合绑定到位于模态/窗口中的列表视图



我有一个wpf应用程序,我希望它能够启动一个单独的窗口,在其中我将有一个绑定到可观察集合的列表视图。但是,我无法使集合值显示在列表视图中。这是一些代码。

窗口(命名向导视图(:

(xaml顶部的数据上下文定义如下(:d: DataContext=";{d:DesignInstance Type=viewModels:MainViewModel}">

<Border Grid.Row="0" Grid.Column="0" Grid.RowSpan="3" BorderBrush="Black">
<ListView BorderThickness="0" ItemsSource="{Binding TestModel.FailedTests}">
<Label Content="Introduction" FontWeight="Bold" />
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel>
<Label Content="{Binding }"/>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Border>

MainViewModel代码:

public class MainViewModel : BaseViewModel
{
public MainViewModel()
{
TestModel = new TestViewModel();
WizardModel = new WizardViewModel(TestModel);
}

private WizardViewModel _wizardModel;
public WizardViewModel WizardModel
{
get
{
return _wizardModel;
}
set
{
_wizardModel = value;
RaisePropertyChanged();
}
}
private TestViewModel _testViewModel;
public TestViewModel TestModel
{
get
{
return _testViewModel;
}
set
{
_testViewModel = value;
RaisePropertyChanged();
}
}

WizardView模型代码:

public class WizardViewModel : TestViewModel
{
internal TestViewModel TestModel;
public WizardViewModel(TestViewModel testModel)
{
TestModel = testModel;
(TroubleShootCommand is defined in seperate UC, and launches fine)
TestModel.TroubleShootCommand = new DelegateCommand(Load, CanTroubleShoot);
}
public void Load()
{
(Sync Root is used because it is running on worker thread. Issue somewhere here?)
_syncRoot.Send(o =>
{
var troubleShootWizard = new WizardView();
troubleShootWizard.Owner = Application.Current.MainWindow;
troubleShootWizard.ShowDialog();
}, null);
}

TestViewModel中的可观察集合(在ctor中初始化(:

private ObservableCollection<string> _failedTests;
public ObservableCollection<string> FailedTests
{
get { return _failedTests; }
set
{
_failedTests = value;
RaisePropertyChanged();
}
}

感谢您的帮助,我觉得我已经尽力了。我通过TestModel下的观察窗口观察了值。启动前后集合中的FailedTests。

首先,

(在xaml顶部这样定义的数据上下文(:d:DataContext=";{d:DesignInstance Type=viewModels:MainViewModel}">

这是一个错误,这样d:您在设计时定义了DataContext。。

您可以通过以下方式在.xaml中创建视图模型:

<WizardView.DataContext>
<viewModels:MainViewModel/>
</WizardView.DataContext>

使用设计时声明在很多方面都有帮助,比如在C#中创建视图模型并分配它(或通过IoC机制(,它还可以帮助IntelliSense和ReSharper等工具分析绑定,并在xaml、自动完成等中拼错属性名称时发出警告

其次,如果您以相同的方式(即设计时间(在.xaml中分配WizardViewModel,那么您可以在Load()函数中执行(添加troubleShootWizard.DataContext = this;(,也可以以我之前提到的相同方式在.xaml中分配。

最新更新