在wpf中获取SelectedItem的值 [英] Get the values of a SelectedItem in wpf

查看:1307
本文介绍了在wpf中获取SelectedItem的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在WPF页面中有一个列表框,每个列表项由两个标签组成.我给他们分配了名字FirstName,LastName:

I have a ListBox in a WPF Page each Item of which consists of two Labels. I have assigned them the names FirstName, LastName:

<ListBox.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="Auto"/>
                        <ColumnDefinition Width="Auto"/>
                    </Grid.ColumnDefinitions>
                    <TextBlock Grid.Column="0" Name="FirstName" Text="{Binding FirstName}" Margin="0,0,10,0"/>
                <TextBlock Grid.Column="1" Name="LastName" Text="{Binding LastName}" HorizontalAlignment="Left"/>
                </Grid>
            </DataTemplate>
        </ListBox.ItemTemplate>

当用户选择列表框的项目时,我想分别保存它们的值,以便将它们传递到另一个页面.为此,我尝试在代码后面的代码中:

When the user selects an Item of the Listbox, I want to hold their values separately in order to pass them to another Page. I try to this end in the code behind the code:

 ListItemCollection lbi = List1.SelectedItem as ListItemCollection;

        string first = lbi.FirstListItem.DataContext.ToString();
        string last = lbi.LastListItem.DataContext.ToString();

但是我在字符串定义中得到了nullReferenceException吗?这样怎么了?如何获取SelectedItem值?

However I get a nullReferenceException at the definition of strings? What is wrong in this way? How can I get the SelectedItem values?

更新:绑定值从带有SQL查询的SQLAdapter派生.参见后面的代码:

Update: The Binding values derive from an SQLAdapter with a SQL Query. See the code behind:

SqlDataAdapter dAdapt1 = new SqlDataAdapter(sqlStr1, cnStr);

        DataSet dataSet1 = new DataSet();
        dAdapt1.Fill(dataSet1);

        List1.DataContext = dataSet1.Tables[0];

推荐答案

DataTable和ListBox ##

myDataSet.BookTable. firstColumn和lastColumn.

DataTable and ListBox##

myDataSet.BookTable. firstColumn and lastColumn.

已准备好绑定

binding ready

1.

adapter.Fill(myDataSet, "BookTable"); 

2.

myListBox.DataContext = myDataSet;

绑定开始

3.XAML

<ListBox ItemsSource="{Binding Path=BookTable}"  

4. Window.Resources>

4. Window.Resources>

<DataTemplate x:Key="BookItemTemplate">
                <Grid>
  <TextBlock Text="{Binding Path=first}" Grid.Column="0"/> 
  <TextBlock Text="{Binding Path=last}" Grid.Column="1" /> 

5.

ItemTemplate ="{StaticResource BookItemTemplate}"/>

绑定结束

6.

DataRowView d1=List1.SelectedItem as DataRowView;
string first =d1["first"].tostring();
string last =d1["last"].tostring();

这篇关于在wpf中获取SelectedItem的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆