如何访问DataGridTemplateColumn中的所有堆栈面板?
我正在使用此代码:
<DataGrid HeadersVisibility="None" Name="dgUser" Grid.Row="0" Grid.Column="0" AutoGenerateColumns="False" ItemsSource="{Binding}"
CanUserAddRows="False" CanUserDeleteRows="False" CanUserSortColumns="False">
<DataGrid.Columns>
<DataGridTemplateColumn Width="*" Header="" IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Margin="10,0,0,0" Grid.Column="0" Name="spGuns">
<TextBlock Margin="0,0,5,0" Text="Count"/>
<TextBox Margin="0,0,5,0" MinWidth="50" Width="Auto" Name="txtCount" Text="{Binding Count}"/>
<TextBlock Margin="0,0,5,0" Text="NameEn"/>
<TextBox Margin="0,0,5,0" MinWidth="50" Width="Auto" Name="txtGunNameEn" Text="{Binding NameEn}"/>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
数据网格中的数据:
http://www.imagetoo.com/?v=untitlfif.png
如何访问DataGridTemplateColumn中的所有堆栈面板?
答案 0 :(得分:0)
像这样在“x:Name”中更改StackPanel的属性“Name”
<StackPanel Orientation="Horizontal" Margin="10,0,0,0" Grid.Column="0" x:Name="spGuns">
<TextBlock Margin="0,0,5,0" Text="Count"/>
<TextBox Margin="0,0,5,0" MinWidth="50" Width="Auto" Name="txtCount" Text="{Binding Count}"/>
<TextBlock Margin="0,0,5,0" Text="NameEn"/>
<TextBox Margin="0,0,5,0" MinWidth="50" Width="Auto" Name="txtGunNameEn" Text="{Binding NameEn}"/>
</StackPanel>
您的StackPanel将以编程方式提供。
答案 1 :(得分:0)
添加此类以遍历dataGrid的每一行
public IEnumerable<DataGridRow> GetDataGridRows(DataGrid grid)
{
var itemsSource = grid.ItemsSource as IEnumerable;
if (null == itemsSource) yield return null;
foreach (var item in itemsSource)
{
var row = grid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
if (null != row) yield return row;
}
}
然后你的问题是找到控制解决方法
foreach (DataGridRow row in GetDataGridRows(dgUser))
{
if (row.IsEnabled)
{
try
{
ContentPresenter cp = dgUser.Columns[i].GetCellContent(row) as ContentPresenter;
DataTemplate myDataTemplate = cp.ContentTemplate;
TextBox t = (TextBox)myDataTemplate.FindName("textBoxName", cp);
t.Text = //Do something
}
catch (Exception)
{ }
}
}