除了在视图模型中为所选项目指定属性,在显示网格的 xaml 中,您可以使用如下内容:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication3"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactions"
xmlns:ie="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" x:Class="WpfApplication3.MainWindow"
x:Name="MyMainWindow">
<Grid>
<DataGrid x:Name="myGrid" ItemsSource="{Binding myItems}">
<ie:Interaction.Triggers>
<ie:EventTrigger EventName="SelectionChanged">
<ie:InvokeCommandAction Command="{Binding SelectedItemChangedCommand}" CommandParameter="{Binding ElementName=myGrid, Path=SelectedItem}"/>
</ie:EventTrigger>
</ie:Interaction.Triggers>
</DataGrid>
</Grid>
然后在您的视图模型中:
public class MainWindowViewModel
{
public MainWindowViewModel()
{
myItems = new ObservableCollection<Person>
{
new Person("John", 23),
new Person("Kobi", 25),
new Person("Lizard", 43)
};
SelectedItemChangedCommand = new DelegateCommand<object>((selectedItem) =>
{
var selected = selectedItem as Person;
// Do whatever you want to display the properties of your selected item
// and let you user change them
});
}
public ObservableCollection<Person> myItems { get; set; }
public DelegateCommand<object> SelectedItemChangedCommand { get; set; }
}
public class Person
{
public Person(string name, int age)
{
Name = name;
Age = age;
}
public string Name { get; set; }
public int Age { get; set; }
}