从WPF的Listview中获取viewmodel中的SelectedItem



我有一个列表视图。我想获得所选Employee的Id。我认为选定的员工将给出选定行的所有细节然后我可以通过selecteemployee。empid获取Id。它不工作

这是我的XAML:

<ListView Grid.Row="1" Name="listViewTask" ItemsSource="{Binding Employees}" SelectedItem="{Binding SelectedEmployee, Mode=TwoWay}"  Margin="1,25,0,10" Foreground="Black" SelectionChanged="ListView_SelectionChanged" Grid.ColumnSpan="2" >
        <ListView.View  >
            <GridView  >
        <GridViewColumn Header="EmpId" Width="100" DisplayMemberBinding="{Binding EmpId}"/>
                    <GridViewColumn Header="Created Date" Width="100" DisplayMemberBinding="{Binding created_date}"/>
    </GridView>
        </ListView.View>
    </ListView>

这是我在ViewModel中的属性:

private string selectedEmployee;
public string SelectedEmployee
{
    get { return this.selectedEmployee; }  
    set
    {
        // Implement with property changed handling for INotifyPropertyChanged
        if (!string.Equals((this.selectedEmployee), value))  
        {
            this.selectedEmployee = value;
            this.RaisePropertyChanged(selectedEmployee); // Method to raise the PropertyChanged event in your BaseViewModel class...
        }
    }
} 

根据您提供的代码,SelectedEmployee的类型是字符串。您试图实现的方式是不可能与这样的代码。要么你错了,要么你需要更多地了解WPF/MVVM。我希望Employees也是IEnumerable<String>型。

如果您想从选定的项目中获得选定的员工ID,首先为employees创建一个数据类,如下所示

public class EmployeeData : INotifyPropertyChanged
{
        public event PropertyChangedEventHandler PropertyChanged;
        private Guid empID;
        public Guid EmpId
        {
            get { return empID; }
            set
            {
                empID = value;
                RaisePropertyChanged(empID);
            }
        }
        private string empName;
        public string EmpName
        {
            get { return empName; }
            set
            {
                empName = value;
                RaisePropertyChanged(empName);
            }
        }
}

然后在你的视图模型中创建一个列表,使它成为你的列表框的itemsource:

private ObservableCollection<EmployeeData> employees;
public ObservableCollection<EmployeeData> Employees
{    
    get
    {
        return employees;
    }    
    set
    {
        employees = value;
        RaisePropertyChanged(“employees”);
    }    
}

还有一个属性用来保存选中的项目,像这样:

private EmployeeData selectedEmployee;
public EmployeeData SelectedEmployee
{
    get { return this.selectedEmployee; }  
    set
    {
        // Implement with property changed handling for INotifyPropertyChanged
        if (!string.Equals((this.selectedEmployee), value))  
        {
            this.selectedEmployee = value;
            this.RaisePropertyChanged(selectedEmployee); // Method to raise the PropertyChanged event in your BaseViewModel class...
        }
    }
} 

确保selectedEmployee类型为EmployeeData,而不是字符串。现在您可以像SelectedEmployee.EmpID

这样访问ID

相关内容

  • 没有找到相关文章

最新更新