我是WPF和MVVM的新手。。。我创建了一个类WorkstationItem
public class WorkstationItem
{
public WorkstationItem() { }
public string Name { get; set; }
public string OS { get; set; }
public List<UpdateItem> Updates { get; set; }
}
UpdateItem是另一个类:
public class UpdateItem
{
public UpdateItem() { }
public string Title { get; set; }
public string KB { get; set; }
}
我创建了一些伪数据:
private List<WorkstationItem> workstations = new List<WorkstationItem>();
workstations.Add(new WorkstationItem
{
Name = "PC01",
OS = "Windows Server 2019",
Updates = new List<UpdateItem>{
new UpdateItem { Title = "Test", KB = "KB123123" },
new UpdateItem { Title = "Test2", KB = "KB123123" }
}
});
workstations.Add(new WorkstationItem
{
Name = "PC02",
OS = "Windows Server 2016",
Updates = new List<UpdateItem>{
new UpdateItem { Title = "Test5", KB = "KB123123" },
new UpdateItem { Title = "Test3", KB = "KB123123" }
}
});
现在我在列表框中显示工作站:
<ListBox x:Name="lbPCs" ItemsSource="{Binding WorkstationItemList}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="40"/>
</Grid.RowDefinitions>
<StackPanel Grid.Column="0">
<TextBlock Text="{Binding Name}" FontSize="12" FontWeight="Bold" />
<TextBlock Text="{Binding OS}" FontSize="9" />
</StackPanel>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
ViewModel:
public ObservableCollection<WorkstationItem> WorkstationItemList { get; set; }
WorkstationManager workstationmanager = WorkstationManager.GetInstance();
WorkstationItemList = new ObservableCollection<WorkstationItem>();
foreach (var k in workstationmanager.GetUpdatelist())
{
WorkstationItemList.Add(k);
}
这很好。。。但是我如何在与所选工作站相关的另一个列表中显示List<UpdateItem> Updates
?
所以我在列表1中选择了一个工作站,并想在列表2中显示相关的更新?
提前感谢!
基本上添加另一个引用现有ListBox的SelectedItem的ListBox或ItemsControl,并绑定到SelectedItem的Updates
集合;大致类似(未经测试(:
<ListBox ItemsSource="{Binding ElementName=lbPCs, Path=SelectedItem.Updates}">
<ListBox .ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<!-- TODO improve alignment+layout -->
<TextBlock Text="{Binding KB}" />
<TextBlock Text="{Binding Title}" />
</StackPanel>
</DataTemplate>
<ListBox .ItemTemplate>
</ListBox>
如果您想对所选项目执行更复杂的操作,但要显示其Updates
,则可能更适合将lbPC的SelectedItem绑定到某个新的ViewModel属性,并将新的ListBox项目源绑定到该VM属性的Updates集合。