【发布时间】:2018-07-03 09:42:42
【问题描述】:
我对 C# 和 WPF 非常陌生。我已经开始了新项目来学习如何一起使用它们以及如何构建 UI。 Bearly 开始我一直坚持使用 listview 集合中的 selecteditem。我试图显示从所选对象中获取的一些基本信息。在表单上我添加了标签和一些按钮。主要目标是打开第二个表格,其中包含有关所选记录的详细信息。但首先我想实现一些简单的东西 - 只是在标签控件中显示记录 ID。我可以获取记录并用记录填充列表框,但是所有尝试读取选定数据的尝试都失败了(标签中没有显示任何内容)。你能帮我看看如何在标签场景中使用 selecteditem 吗?并希望给我一些关于详细信息窗口场景的建议...... 无论如何 - 所有关于我的代码的 cmets 都将不胜感激,请耐心等待,记住这是我第一次处理这个问题。
为方便起见,BitBucket 提供了所有代码:https://bitbucket.org/is-smok/gama
感谢您的帮助。
MainWindow.xaml 文件的一部分
<Grid>
<ListView x:Name="lstInventory" Height="180" Margin="5,51,79,0" VerticalAlignment="Top"
ItemsSource="{Binding GetInventory}"
SelectedItem="{Binding SelectedInventory, Mode=TwoWay}"
DisplayMemberPath="Inventory_id">
<ListView.View>
<GridView>
<GridViewColumn Header="GamaID" DisplayMemberBinding="{Binding Inventory_id}" />
<GridViewColumn Header="Typ" DisplayMemberBinding="{Binding Serial_number}" />
<GridViewColumn Header="Producent" DisplayMemberBinding="{Binding Registry_number}" />
</GridView>
</ListView.View>
</ListView>
<Button Content="Add" HorizontalAlignment="Left" Margin="57,265,0,0" VerticalAlignment="Top" Width="75" Click="AddInventory_Click"/>
<Button Content="Remove" HorizontalAlignment="Left" Margin="137,265,0,0" VerticalAlignment="Top" Width="75" Click="RemoveInventory_Click"/>
<Button Content="Edit" HorizontalAlignment="Left" Margin="217,265,0,0" VerticalAlignment="Top" Width="75" Click="EditInventory_Click"/>
<Label Content="{Binding SelectedInventory.Serial_number}" HorizontalAlignment="Left" Margin="120,326,0,0" VerticalAlignment="Top" Height="24" Width="140"/>
<Label x:Name="lblInventoryId" Content="{Binding SelectedInventory.Inventory_id}" HorizontalAlignment="Left" Margin="10,326,0,0" VerticalAlignment="Top" Height="24" Width="105"/>
</Grid>
MainWindow.xaml.cs 的一部分
public MainWindow()
{
InitializeComponent();
DataAccess dataAccess = new DataAccess();
inventory = dataAccess.GetIventory();
lstInventory.ItemsSource = inventory;
lstInventory.DisplayMemberPath = "inventory_id";
}
DataAccess.cs 文件的一部分
private Inventory m_SelectedInventory;
public Inventory SelectedInventory
{
get
{
return m_SelectedInventory;
}
set
{
m_SelectedInventory = value;
}
}
【问题讨论】:
-
你应该先阅读Data Binding Overview。这里有一些错误或缺失的地方。 1. 将dataAccess对象分配给Window的DataContext:
DataContext = dataAccess;。 2.将GetInventory方法变成属性Inventory,像ItemsSource="{Binding Inventory}"一样绑定,去掉lstInventory.ItemsSource = inventory。 3. 使DataAccess实现INotifyPropertyChanged接口并从SelectedInventorysetter触发PropertyChanged事件。 -
@Clemens 谢谢你的回复。 Inventory GetInventory 方法和 Inventory 对象用于填充 ListView。这是我项目中唯一有效的部分。但我会尝试遵循您的建议并使其发挥作用。但首先要阅读建议的文档。泰。
标签: c# wpf listview selecteditem