Wpf 在按钮上获取 DataGrid 的行号单击甚至 C#
Wpf getting the row number of DataGrid on button click even C#
我在 DataGrid 的每一行内都有 2 个按钮。它们将用于保存已编辑的行信息,或者用于删除行。但我无法检索点击事件的行号。
(我的 Whosebug 上也有类似的问题,但 none 对我有用)
<DataTemplate x:Key="myTemplate">
<StackPanel Orientation="Horizontal">
<Button Height="21" Width="21" Margin="4" Style="{StaticResource InformButton}" Click="ClientSave">
<StackPanel Height="17" Width="20">
<Image Source="pack://application:,,,/TimeCounter;component/resources/save.png" Height="14" Width="14" Margin="-1,0" HorizontalAlignment="Left"/>
</StackPanel>
</Button>
<Button Height="21" Width="21" HorizontalAlignment="Right" Margin="4" Style="{StaticResource InformButton}">
<StackPanel Height="18" Width="21">
<Image Source="pack://application:,,,/TimeCounter;component/resources/delete.png" Height="14" Width="13" Margin="0 ,0" HorizontalAlignment="Left"/>
</StackPanel>
</Button>
</StackPanel>
</DataTemplate>
如果遇到事件,我会使用绑定来检索数据项及其索引。
在事件处理程序中:
var btn = sender as Button;
var item = btn.GetBindingExpression(Button.DataContextProperty).DataItem as YourRowItemClass;
var index = YourViewModel.ItemCollection.IndexOf(item);
查看模型:
class YourViewModel : INotifyPropertyChanged {
ObservableCollection<RowItem> ItemCollection { get; private set; }
}
在你的按钮中 XAML:
DataContext="{Binding}"
我在 DataGrid 的每一行内都有 2 个按钮。它们将用于保存已编辑的行信息,或者用于删除行。但我无法检索点击事件的行号。 (我的 Whosebug 上也有类似的问题,但 none 对我有用)
<DataTemplate x:Key="myTemplate">
<StackPanel Orientation="Horizontal">
<Button Height="21" Width="21" Margin="4" Style="{StaticResource InformButton}" Click="ClientSave">
<StackPanel Height="17" Width="20">
<Image Source="pack://application:,,,/TimeCounter;component/resources/save.png" Height="14" Width="14" Margin="-1,0" HorizontalAlignment="Left"/>
</StackPanel>
</Button>
<Button Height="21" Width="21" HorizontalAlignment="Right" Margin="4" Style="{StaticResource InformButton}">
<StackPanel Height="18" Width="21">
<Image Source="pack://application:,,,/TimeCounter;component/resources/delete.png" Height="14" Width="13" Margin="0 ,0" HorizontalAlignment="Left"/>
</StackPanel>
</Button>
</StackPanel>
</DataTemplate>
如果遇到事件,我会使用绑定来检索数据项及其索引。
在事件处理程序中:
var btn = sender as Button;
var item = btn.GetBindingExpression(Button.DataContextProperty).DataItem as YourRowItemClass;
var index = YourViewModel.ItemCollection.IndexOf(item);
查看模型:
class YourViewModel : INotifyPropertyChanged {
ObservableCollection<RowItem> ItemCollection { get; private set; }
}
在你的按钮中 XAML:
DataContext="{Binding}"