我有一个带有一些文本框和一个DataGrid的WPF窗口。 DataGrid充满了Data,但我需要的是,当用户单击该DataGrid中的单元格时,程序会检测该行并使用该行中的数据重新填充文本框。 例如,有一个ID,Name和BirthDate文本框。当用户单击给定行中的任何单元格时,文本框ID,Name和BirthDate的值必须成为所选行中各自列(ID,Name,BirthDate)的值。 我四处寻找答案,但我似乎只找到了与WinForms相关的答案,WinForms和WPF中的DataGrid在代码方面的工作方式完全不同。
答案 0 :(得分: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>
答案 1 :(得分: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; }
}