[英]Unable to bind the collection to Listview in WPF application?
I am developing a WPF application where i can read some properties from the windows services list which are currently running on my system.I am able to read the properties of a particular service and passing to a collection which in turn show up in my UI under a Listview. 我正在开发一个WPF应用程序,可以在其中读取当前正在系统上运行的Windows服务列表中的某些属性。我能够读取特定服务的属性并将其传递给一个集合,该集合又显示在我的UI下列表视图。
I want the same scenario to be used for list of services .iei am trying in the following way..but i am not sure where did i miss the point... 我希望将相同的方案用于服务列表。即,我正以以下方式尝试..但我不确定我错过了重点...
Here is my code 这是我的代码
foreach (string serviceName in sList)
{
ServiceController controller = new ServiceController(serviceName);
StatusCollection.Add (new StatusData
{
Name = name,
Status = status
});
lvStatus.DataContext = StatusCollection;
lvStatus.ItemsSource = StatusCollection;
}
<ListView Height="166" HorizontalAlignment="Left" Margin="23,0,0,0" Name="lvStatus" VerticalAlignment="Top" Width="264" >
<ListView.View>
<GridView>
<GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"></GridViewColumn>
<GridViewColumn Header="Status" DisplayMemberBinding="{Binding Status}"></GridViewColumn>
</GridView>
</ListView.View>
</ListView>
Remove the DataContext line of code. 删除DataContext代码行。
If you set your ItemsSource in the code behind make sure you do it before InitializeComponent is called. 如果您在后面的代码中设置了ItemsSource,请确保在调用InitializeComponent之前进行了设置。 If not, you will need to refresh your Items collection. 如果没有,则需要刷新Items集合。
However, I would setup a View Model for your Window or Control which implements INotifyPropertyChanged. 但是,我将为实现INotifyPropertyChanged的窗口或控件设置一个视图模型。 Create your collection as an ObservableCollection and bind to it in the XAML: 将您的集合创建为ObservableCollection并将其绑定到XAML中:
<ListView ... ItemsSource={Binding Path=ServiceList}>
<ListView.View>
<GridView>
<GridViewColumn Header="Name" DisplayMemberBinding="{Binding Path=Name}" />
<GridViewColumn Header="Status" DisplayMemberBinding="{Binding Path=Status}" />
</GridView>
</ListView.View>
</ListView>
Let me know if you need an example of using a View Model. 让我知道您是否需要使用视图模型的示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.