WPF C#获取选定的行项目Listview

时间:2014-08-27 15:10:19

标签: c# wpf listview data-binding

我有一个弹出ListView,以这种方式声明:

<ListView x:Name="ShowFileLV" 
          ItemsSource="{Binding EmployeeCollection}" 
          DataContext="{Binding}" 
          SelectedItem="{Binding Path=SelectedEmployee}" 
          SelectionMode="Single">
    <ListView.View>
        <GridView>
            <GridViewColumn Width="140" 
                            DisplayMemberBinding="{Binding Name}">
                <GridViewColumnHeader Click="SortClick"   
                                      Tag="Name" 
                                      Content="Name" />
            </GridViewColumn>
            <GridViewColumn Width="140" 
                            DisplayMemberBinding="{Binding ID}">
                <GridViewColumnHeader Click="SortClick"
                                      Tag="ID" 
                                      Content="ID" />
            </GridViewColumn>
        </GridView>
    </ListView.View>
</ListView>

列表和排序工作正常。我的问题是,当我选择一行(不确定ListViewItem是否是正确的选择)时,我想直接更新SelectedEmployee,或者甚至更好,只获取ID或名称:

public ListViewItem SelectedEmployee
{
    get
    {
        return _selectedEmployee;
    }
    set
    {
        _selectedEmployee= value;           
    }
}

这一直有效,直到我使用一个ListBox(而不是ListView)加载了一个字符串列表,每个字符串都包含Name和ID,就像这个

<ListBox Name="ShowFileLV" 
         SelectionMode="Single" 
         SelectedValue="{Binding Path=Employee}" 
         Style="{StaticResource ListBoxStyle}" ItemsSource="{Binding Path=ListPopupItems}" >
</ListBox>

使用公共字符串,如:

public String Employee
{
    get
    {
        return _employee;
    }
    set
    {
        _employee= value;
        OnPropertyChanged("Employee");
    }
}

当我选择一行时,它会自动设置公共字符串Employee,而不需要代码。 我怎样才能使用ListView和Collections?

1 个答案:

答案 0 :(得分:0)

SelectedItem绑定会将值设置为集合EmployeeCollection中的类型。因此,假设EmployeeCollection是ObservableCollection<Employee>,您需要将SelectedEmployee从ListViewItem更改为Employee。另外,请确保使用INotifyPropertyChanged界面。

public Employee SelectedEmployee
{
    get
    {
        return _selectedEmployee;
    }
    set
    {
        _selectedEmployee= value;
        RaisePropertyChanged("SelectedEmployee");
    }
}

如果只想要名称或ID,则使用SelectedValue和SelectedValuePath而不是SelectedItem。

<ListView x:Name="ShowFileLV" 
          ItemsSource="{Binding EmployeeCollection}" 
          DataContext="{Binding}" 
          SelectedValue="{Binding Path=SelectedEmployee}"
          SelectedValuePath="Name"
          SelectionMode="Single"> 

public string SelectedEmployee
{
    get { return _selectedEmployee; }
    set
    {
       _selectedEmployee = value;
       RaisePropertyChanged("SelectedEmployee");
    }
}