我有一个列表视图。我想获得所选员工的ID。 我以为Selected Employee会给出所选行的所有细节 然后我可以通过SelectedEmployee.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...
}
}
}
答案 0 :(得分:0)
根据您提供的代码,SelectedEmployee
的类型为字符串。使用这样的代码无法实现您尝试实现的方式。
要么你错了,要么你需要了解更多关于WPF / MVVM的知识。我希望Employees
也是IEnumerable<String>
类型。
如果您想从所选项目中获取所选员工ID,请首先为员工创建此类数据类
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);
}
}
}
然后在你的viewmodel中创建一个这样的列表并将其作为列表框的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
,而不是字符串。
现在,您可以访问ID SelectedEmployee.EmpID