我有一个带有一些文本框和一个 DataGrid 的 WPF 窗口。DataGrid 填充了数据,但我需要这样,当用户单击该 DataGrid 中的单元格时,程序会检测到该行并用该行中的数据重新填充文本框。例如,有一个 ID、Name 和 BirthDate 文本框。当用户单击给定行中的任何单元格时,文本框 ID、Name 和 BirthDate 的值必须成为所选行中它们各自列(ID、Name、BirthDate)的值。我四处寻找答案,但我似乎只找到与 WinForms 相关的答案,而 WinForms 和 WPF 中的 DataGrid 的工作方式完全不同,代码方面。
问问题
6646 次
2 回答
5
您可以简单地使用Binding
该ElementName
属性为您执行此操作...不需要后面的代码:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<DataGrid Name="DataGrid" ItemsSource="{Binding YourDataCollection}" />
<Grid Grid.Column="1">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Text="{Binding SelectedItem.Id,
ElementName=DataGrid}" />
<TextBlock Grid.Row="1" Text="{Binding SelectedItem.Name,
ElementName=DataGrid}" />
<TextBlock Grid.Row="2" Text="{Binding SelectedItem.BirthDate,
ElementName=DataGrid}" />
</Grid>
</Grid>
于 2013-10-16T09:20:46.730 回答
0
在这里,我按照您的原始示例做了一个小插图:
//XAML
<Grid>
<DataGrid ItemsSource="{Binding Persons}" Margin="0,0,136,0" SelectedItem="{Binding SelectedPerson}"></DataGrid>
<Label Content="{Binding SelectedPerson.Id}" HorizontalAlignment="Left" Margin="400,35,0,0" VerticalAlignment="Top" Width="90" Height="26"/>
<Label Content="{Binding SelectedPerson.Name}" HorizontalAlignment="Left" Margin="400,97,0,0" VerticalAlignment="Top" Width="90" Height="24"/>
<Label Content="{Binding SelectedPerson.BirthDate}" HorizontalAlignment="Left" Margin="400,66,0,0" VerticalAlignment="Top" Width="90" Height="26"/>
</Grid>
//.cs
public MainWindow()
{
InitializeComponent();
DataContext = new PersonViewModel();
}
//ViewModel
public class PersonViewModel : INotifyPropertyChanged
{
private Person _selectedPerson;
public List<Person> Persons { get; set; }
public Person SelectedPerson
{
get { return _selectedPerson; }
set { _selectedPerson = value; OnPropertyChanged("SelectedPerson"); }
}
public PersonViewModel()
{
Persons = new List<Person>
{
new Person(){Id = 1,BirthDate = DateTime.Now.AddYears(-30),Name = "Mark"},
new Person(){Id = 2,BirthDate = DateTime.Now.AddYears(-40), Name = "Sophy"},
new Person(){Id = 3,BirthDate = DateTime.Now.AddYears(-50), Name = "Bryan"},
};
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
// Model
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime BirthDate { get; set; }
}
于 2013-10-15T22:49:13.527 回答