C# 将选定的DataGrid行绑定到textbox
我想将文本框绑定到选定的C# 将选定的DataGrid行绑定到textbox,c#,wpf,data-binding,C#,Wpf,Data Binding,我想将文本框绑定到选定的DataGrid。我已经将列表绑定到datagrid,但现在我想将文本框文本绑定到datagrid所选行,以便将其内容放入文本框 txtOccArea.DataContext = hegData; //hegData is a list of an object 谢谢 如果您只想在文本框中显示该值,可以在XAML中绑定。试试这个: <DataGrid x:Name="MyGrid" ItemsSource="{Binding hegData}"/> <
DataGrid
。我已经将列表绑定到datagrid,但现在我想将文本框
文本绑定到datagrid
所选行,以便将其内容放入文本框
txtOccArea.DataContext = hegData;
//hegData is a list of an object
谢谢 如果您只想在文本框中显示该值,可以在XAML中绑定。试试这个:
<DataGrid x:Name="MyGrid" ItemsSource="{Binding hegData}"/>
<TextBox Text={Binding SelectedItem, ElementName=MyGrid}/>
如果您确实需要更改所选项目,我认为您应该在ViewModel中定义SelectedListItem属性,并将文本框的文本绑定到此属性
视图模型:
public List<object> hegData {get;set;}
public object SelectedListItem {get;set;}
公共列表hegData{get;set;}
公共对象SelectedListItem{get;set;}
视图:
您应该创建这样的新类(我希望您使用的是MVVM) 在你创建它的地方,你可以这样称呼它:
YourViewVM yourViewVM = new YourViewVM(hegData)
到目前为止你试过什么??请张贴一些代码刚刚更新我的POST你实际上应该考虑绑定列表的选择值的值TBXBX如何获得列表中的选定值?使用datagrid?感谢您的帮助@汉克斯很高兴它能帮上忙:)
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>
public YourViewVM(List<YourObject> hegData)
{
this.DataGridSource = hegData;
}
YourViewVM yourViewVM = new YourViewVM(hegData)