WPF ListView 2列SelectedItem

时间:2015-03-17 13:55:03

标签: wpf listview data-binding selecteditem

我使用数据绑定编写了一个ListView。一切正常,但现在我想在用户选择一行时获取所选项目。

这是我的XAML代码:

<Window x:Class="TableTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="600" Width="700">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="100"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="200"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>

        <Button Grid.Column="1" Height="25" Width="75" HorizontalAlignment="Right" Margin="0,0,50,0"  
                x:Name="renewData" Content="Aktualisieren" Click="renewData_Click" />

        <ListView x:Name="AccountOverview" ItemsSource="{Binding Users}" 
                  SelectedItem="{Binding SelectedItem, Mode=TwoWay}" Grid.Row="1" Grid.Column="0">
            <ListView.View>
                <GridView AllowsColumnReorder="true">
                    <GridViewColumn DisplayMemberBinding="{Binding Path=Sam}" Header ="SAM" Width="125"/>
                    <GridViewColumn DisplayMemberBinding="{Binding Path=Active}" Header="Aktive" Width="75"/>
                </GridView>
            </ListView.View>
        </ListView>
        <!-- Detailansicht Benutzer -->
        <Grid Grid.Column="1" Grid.Row="1">
            <Grid.RowDefinitions>
                <RowDefinition Height="*"/>
                <RowDefinition Height="200"/>
            </Grid.RowDefinitions>
            <Grid Grid.Row="0">
                <StackPanel DataContext="AccountDetailViewModel">
                    <StackPanel Orientation="Horizontal">
                        <Label Content="Account Daten"/>
                    </StackPanel>
                    <StackPanel Orientation="Horizontal">
                        <Label Content="SAMAccountName" Width="200"/>
                        <TextBox x:Name="SAMAccountName" Margin="0,8,0,0" Width="150" Text="{Binding samAccountName}"/>
                    </StackPanel>
                    <StackPanel Orientation="Horizontal">
                        <Label Content="Aktivierung (UserAccountControl)" Width="200"/>
                        <TextBox x:Name="UserAccountControl" Margin="0,8,0,0" Width="150" Text="{Binding userAccountControl}"/>
                    </StackPanel>
                    <StackPanel Orientation="Horizontal">
                        <Label Content="lastLogonTimestamp" Width="200"/>
                        <TextBox x:Name="lastLogonTimestamp" Margin="0,8,0,0" Width="150" Text="{Binding lastLoginTimestamp}"/>
                    </StackPanel>
                    <StackPanel Orientation="Horizontal">
                        <Label Content="pwdLastSet" Width="200"/>
                        <TextBox x:Name="pwdLastSet" Margin="0,8,0,0" Width="150" Text="{Binding pwdLastSet}"/>
                    </StackPanel>
                    <StackPanel Orientation="Horizontal">
                        <Label Content="objectSID" Width="200" />
                        <TextBox x:Name="objectSID" Margin="0,8,0,0" Width="150" Text="{Binding objectSID}"/>
                    </StackPanel>
                </StackPanel>
            </Grid>
            <StackPanel Grid.Row="1">
                <Label Content="Account Aktionen"/>
                <Label Content="Passwort setzen"/>
                <Label Content="Account löschen"/>
                <Label Content="Account sperren"/>
            </StackPanel>
        </Grid>
    </Grid>
</Window>

DataBinding工作正常。在我的ViewModel中,我为选择创建了一个变量SelectedItem,但我只得到值TableTest.Account作为输出而不是Sam名称。这是我背后的代码

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.DirectoryServices;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace TableTest
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public ViewModel vm = new ViewModel();
        public DirectoryEntry DCE;
        public MainWindow()
        {
            InitializeComponent();
            Window LoginWindow = new LoginWindow(this);
            //Zeige Login Page
            //LoginWindow.Show();
            if (!LoginWindow.IsVisible)
            {
                LoginWindow.Show();
            }
            if (LoginWindow.WindowState == WindowState.Minimized)
            {
                LoginWindow.WindowState = WindowState.Normal;
            }
            this.DataContext = vm;
        }
        /*Liest die Gruppenmitglieder mithilfe der DC Entry Elements aus*/
        public void getGroupAccounts()
        { 
            ActiveDirectoryInterface ActiveDirectoryInterface = new ActiveDirectoryInterface();
            vm.Users = ActiveDirectoryInterface.loadAccounts();

            Debug.WriteLine("Benutzer gehil");
        }
        public void setDCE(DirectoryEntry DCE) 
        {
            this.DCE = DCE;
        }

        private void renewData_Click(object sender, RoutedEventArgs e)
        {
            ((ViewModel)DataContext).renewListData();
        }
    }

#region ViewModel
    public class ViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        #region NormMethods
        public void updateAccountDetail()
        {
            /*Raussuchen des selektierten Benutzers und dann Übergabe an das DetailViewModel um Anzeige zu ändern*/
            /*Benutzen von Linq um die ObservableCollection zu durchsuchen und dann den Benutzer auszulesen und in der
              Variable toDetail zu speichern */
            Debug.WriteLine("searching for: " + _selectedItem);
            Account toDetail = _users.Where(X => X.Sam == _selectedItem).FirstOrDefault();
            if (toDetail != null)
            {
                Debug.WriteLine("ungleich null");
            }
            else {
                Debug.WriteLine("gleich null");
            }

            //AccountDetailViewModel AccountDetailViewModel = new AccountDetailViewModel();
            //Debug.WriteLine(toDetail.Sam.ToString());


            //AccountDetailViewModel.updateView(toDetail);
        }
        #endregion
        #region Eventhandler
        public void renewListData() 
        {
            Users.Add(new Account { Sam = "Cheg", Active = "Immer" });
            Debug.WriteLine("User Added");
        }
        #endregion 
        #region DataBinding

        public string _selectedItem;
        public string SelectedItem
        {
            get { return _selectedItem; }
            set
            {
                _selectedItem = value;
                OnPropertyChanged();
                Debug.WriteLine("Selektion changed: " + value);
                //updateAccountDetail();
            }
        }
        public ObservableCollection<Account> _users;
        public ObservableCollection<Account> Users 
        {
            get { return _users;  }
            set 
            { 
                _users = value;
                OnPropertyChanged();
            } 
        }
        public ViewModel()
        {
            Users = new ObservableCollection<Account>()
            {
                new Account { Sam = "1", Active ="Test Last Name 1"}, 
                new Account { Sam = "2", Active ="Test Last Name 2"}, 
            };
        }
        protected virtual void OnPropertyChanged(string propertyName = null)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion
    }
#endregion
}

有人可以告诉我,我做错了什么?当选择更改时,我只想要第一列的值。 谢谢你的帮助 :)!

1 个答案:

答案 0 :(得分:0)

SelectedItem属性应返回在UI中选择的数据元素。在您的情况下,这将是您的Users集合中的元素。因此,您应该能够从该对象访问Sam属性,如下所示:

string samValueFromSelectedItem = SelectedItem.Sam;