简体   繁体   English

WPF获得按钮上的DataGrid的行号单击甚至C#

[英]Wpf getting the row number of DataGrid on button click even C#

I have 2 buttons inside every row of DataGrid. 我在DataGrid的每一行中都有2个按钮。 They will be used to either save edited row info, either to delete row. 它们将用于保存编辑后的行信息,或者用于删除行。 But I can't retrieve the row number on click event. 但是我无法在点击事件中检索行号。 (there are similar issues on stackoverflow to mine, but none worked for me) (我的stackoverflow也有类似的问题,但对我没有作用)

 <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>

If stuck to event, I would use binding to retrieve data item, and its index. 如果卡在事件上,我将使用绑定来检索数据项及其索引。

In event handler: 在事件处理程序中:

var btn = sender as Button;
var item = btn.GetBindingExpression(Button.DataContextProperty).DataItem as YourRowItemClass;
var index = YourViewModel.ItemCollection.IndexOf(item);

View model: 查看模型:

class YourViewModel : INotifyPropertyChanged {
    ObservableCollection<RowItem> ItemCollection { get; private set; }
}

In your button XAML: 在您的按钮XAML中:

DataContext="{Binding}"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM