我想将文本框绑定到选定的DataGrid
. 我已经将列表绑定到数据网格,但现在我想将TextBox
文本绑定到DataGrid
所选行,以便将其内容放入TextBox
txtOccArea.DataContext = hegData;
//hegData is a list of an object
谢谢!
您应该创建一个这样的新类(我希望您使用的是 MVVM)。
public class YourViewVM : INotifyPropertyChanged
{
#region Fields
private object selectedDataGridCell;
private string textBoxContent;
private List<YourObject> dataGridSource;
#endregion
#region Properties
public object SelectedDataGridCell
{
get
{
return this.selectedDataGridCell;
}
set
{
if (this.selectedDataGridCell != value)
{
this.selectedDataGridCell = value;
OnPropertyChanged("SelectedDataGridCell");
}
}
}
public string TextBoxContent
{
get
{
return this.textBoxContent;
}
set
{
if (this.textBoxContent != value)
{
this.textBoxContent = value;
OnPropertyChanged("TextBoxContent");
}
}
}
public List<YourObject> DataGridSource
{
get
{
return this.dataGridSource;
}
set
{
if (this.dataGridSource != value)
{
this.dataGridSource = value;
OnPropertyChanged("Source");
}
}
}
#endregion
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
在您看来,只需将其修改为:
<Grid>
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<DataGrid ItemsSource="{Binding DataGridSource}" SelectedItem="{Binding SelectedDataGridCell}" />
<TextBox Grid.Row="1" Text="{Binding TextBoxContent}"></TextBox>
</Grid>
您需要添加INotifyPropertyChanged
以便TextBox
知道选择何时更改。
如果您需要将 DataGridSource 设置为您的hegData
列表,只需创建一个构造函数并在那里设置属性,如下所示:
public YourViewVM(List<YourObject> hegData)
{
this.DataGridSource = hegData;
}
在您创建它的地方,只需将其命名为:
YourViewVM yourViewVM = new YourViewVM(hegData)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句