我想将文本框绑定到选定的DataGrid
。我已经将列表绑定到数据网格,但是现在我想将TextBox
文本绑定到DataGrid
选择的行,以便将其内容放入TextBox
txtOccArea.DataContext = hegData;
//hegData is a list of an object
谢谢!
答案 0 :(得分:1)
您应该创建一个像这样的新类(希望您正在使用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)
答案 1 :(得分:0)
如果只想在TextBox中显示值,则可以在XAML中进行绑定。试试这个:
<DataGrid x:Name="MyGrid" ItemsSource="{Binding hegData}"/>
<TextBox Text={Binding SelectedItem, ElementName=MyGrid}/>
如果您确实需要更改Selected Item,我认为您应该在ViewModel中定义SelectedListItem属性,并将TextBox的文本绑定到该属性。
ViewModel:
public List<object> hegData {get;set;}
public object SelectedListItem {get;set;}
查看:
<DataGrid ItemsSource="{Binding hegData}"
SelectedItem="{Binding SelectedListItem}"/>
<TextBox Text={Binding SelectedListItem}/>