我正在寻找一些我正在写的WPF窗口的帮助。我想从一个非常混乱的ListView
中获取特定列的值。这是XAML:
<Grid>
<ListView Name="listViewItem" ClipToBounds="True" VerticalContentAlignment="Stretch" HorizontalContentAlignment="Stretch" SizeChanged="ListView_SizeChanged" Loaded="ListView_Loaded" TextOptions.TextHintingMode="Animated" Margin="0,0,83,0">
<ListView.View>
<GridView AllowsColumnReorder="False">
<GridViewColumn Header="Company Name" Width="150">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding CompanyName}" TextWrapping="Wrap" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Company Address" Width="350">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding CompanyAddress}" TextWrapping="Wrap" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
</Grid>
listViewitem.SelectedItem
或SelectedItems
有任何会让我访问这些值的成员。访问子项也是不可能的,它们甚至都没有出现。
这就是我绑定的方式。
private void ListView_Loaded(object sender, RoutedEventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["DB"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand("SELECT CompanyName, CompanyAddress FROM Groups", connection);
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataTable dt = new DataTable("Groups");
adapter.Fill(dt);
listViewItem.ItemsSource = dt.DefaultView;
}
}
答案 0 :(得分:0)
您可以将SelectedItem
转换为定义CompanyName
和CompanyAddress
属性的类型:
var selectedItem = listViewItem.SelectedItem as DataRowView;
if(selectedItem != null)
{
string name = selectedItem["CompanyName"].ToString();
...
}