开发者

WPF DataGrid Button Click in New Line Gets the wrong line in Current Item

开发者 https://www.devze.com 2023-02-19 07:35 出处:网络
I have a WPF DataGrid with a b开发者_如何学Cutton on one of the columns. When I click the button I have this function called:

I have a WPF DataGrid with a b开发者_如何学Cutton on one of the columns. When I click the button I have this function called:

MyClass mySC = (MyClass)(CollectionViewSource.GetDefaultView(grdMyClass.DataContext).CurrentItem);

This code works perfect, but when I click on the button on the new line (the last on on the grid) I get the msSC of the line before it, and not null, or something that related to the last new line.

how can I check if the button was clicked in the new line ?


If your intention is that clicking on a button should do something with the data bound to that row then just get the data from the button's data context. If null then user clicked on an empty row.

private void Button_Click(object sender, RoutedEventArgs e)
{
    MyClass data = (sender as FrameworkElement).DataContext as MyClass;
}


I just got the exact same problem and created my own solution.

I have a DataGrid with ItemsSource binded to a list in my ViewModel, and SelectedIndex binded to an int in the viewmodel, in order to be able to play with the list when we choose something (and for example simulate an event such as "OnSelectionChanged")

So the solution is very simple here:

//App selected on the list
private int _selectedApp;

public int SelectedApp
{
    get { return _selectedApp; }
    set 
    {
        if (value == _listApps.Count) _selectedApp = -1;
        else _selectedApp = value;
        OnPropertyChanged("SelectedApp");
    }
}

I just check that the index isn't out of range: if it is, I set it to -1, so my app considers nothing is actually selected.

Hope this can help, feel free to ask more :)

0

精彩评论

暂无评论...
验证码 换一张
取 消