我想获取存储在DataGrid
的第一个单元格中的值。当有人点击我的xaml上的更新Button
时,我该如何解析该值?
Xaml代码
<DataGrid Name="GridStream" Style="{StaticResource GridDatabase}" Margin="5" Grid.Row="1" ItemsSource="{Binding}" AutoGenerateColumns="False" >
<DataGrid.Resources>
<Style TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="Background" Value="Turquoise"/>
<Setter Property="Foreground" Value="Black"/>
<Setter Property="FontWeight" Value="SemiBold"/>
<Setter Property="Padding" Value="5"/>
<Setter Property="BorderThickness" Value="0,0,1,2"/>
<Setter Property="BorderBrush" Value="Black"/>
</Style>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTextColumn Header="Stream Id" Width="*" Binding="{Binding streamid}" />
<DataGridTextColumn Header="Stream Name" Width="*" Binding="{Binding streamname}" />
<DataGridTemplateColumn>
<DataGridTemplateColumn.HeaderTemplate>
<DataTemplate>
<TextBlock Text="Action"></TextBlock>
</DataTemplate>
</DataGridTemplateColumn.HeaderTemplate>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Button Name="BtnUpdateStream" Content="Update" Style="{StaticResource BtnForm}" Click="BtnUpdateStream_Click"/>
<Button Name="BtnDeleteStream" Content="Delete" Style="{StaticResource BtnForm}" Click="BtnDeleteStream_Click"/>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
C#代码段
private void BtnUpdateStream_Click(object sender, RoutedEventArgs e)
{
int Id = (GridStream.SelectedItem as member).streamid;
UpdateStream NewForm = new UpdateStream(Id);
Console.WriteLine("The Id Value : {0} is", Id);
//MessageBox.Show(Id);
NewForm.Show();
}
答案 0 :(得分:1)
如果ItemsSource
中的DataGrid
是IEnumerable<member>
,这应该可以工作:
private void BtnUpdateStream_Click(object sender, RoutedEventArgs e)
{
var x = GridStream.SelectedItem as member;
if (x != null)
{
int Id = x.streamid;
UpdateStream NewForm = new UpdateStream(Id);
NewForm.Show();
}
}
如果没有选择项,或者当前选择项的类型不是member
,则不会显示该表格。
如果将ItemsSource
设置为DataView
,则应该可以:
var x = GridStream.SelectedItem as DataRowView;
if (x != null)
{
int Id = Convert.ToInt32(x["streamid"]);
UpdateStream NewForm = new UpdateStream(Id);
NewForm.Show();
}
如果要绑定到匿名类型的IEnumerable
,则可以使用dynamic
关键字
private void BtnUpdateStream_Click(object sender, RoutedEventArgs e)
{
dynamic x = GridStream.SelectedItem;
if (x != null)
{
int Id = x.streamid;
//...
}
}