使用来自NuGet的MVVM 灯的工作示例。
您可以在下部文本框中写入索引以查看它在 DataGrid 上的变化。
主窗口.xaml
<Window
x:Class="Test_DataGridSelectedIndexItem.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:testDataGridSelectedIndexItem="clr-namespace:Test_DataGridSelectedIndexItem"
Title="MainWindow"
Height="350"
Width="525"
>
<Window.DataContext>
<testDataGridSelectedIndexItem:MainViewModel />
</Window.DataContext>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height=".9*"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<DataGrid
Grid.Row="0"
ItemsSource="{Binding Items}"
SelectedItem="{Binding Selected, Mode=TwoWay}"
SelectedIndex="{Binding SelectedIndex, Mode=TwoWay}"
/>
<TextBlock
Grid.Row="1"
Text="{Binding Selected}"
/>
<TextBlock
Grid.Row="2"
Text="{Binding SelectedIndex}"
/>
<TextBox
Grid.Row="3"
Text="{Binding SelectedIndex, Mode=TwoWay}"
/>
</Grid>
</Window>
主视图模型.cs
using System.Collections.ObjectModel;
using GalaSoft.MvvmLight;
namespace Test_DataGridSelectedIndexItem
{
public class MainViewModel : ViewModelBase
{
private ItemViewMode selected;
private int selectedIndex;
public MainViewModel()
{
this.Items = new ObservableCollection<ItemViewMode>()
{
new ItemViewMode("Item1"),
new ItemViewMode("Item2"),
new ItemViewMode("Item3"),
};
}
public ObservableCollection<ItemViewMode> Items { get; private set; }
public ItemViewMode Selected
{
get
{
return this.selected;
}
set
{
this.selected = value;
this.RaisePropertyChanged(() => this.Selected);
}
}
public int SelectedIndex
{
get
{
return this.selectedIndex;
}
set
{
this.selectedIndex = value;
this.RaisePropertyChanged(() => this.SelectedIndex);
}
}
}
}
项目视图模型.cs
using GalaSoft.MvvmLight;
namespace Test_DataGridSelectedIndexItem
{
public class ItemViewModel : ViewModelBase
{
private string text;
public ItemViewModel() : this(string.Empty)
{
}
public ItemViewModel(string text)
{
this.text = text;
}
public string Text
{
get
{
return this.text;
}
set
{
this.text = value;
this.RaisePropertyChanged(() => this.Text);
}
}
public override string ToString()
{
return this.text;
}
}
}