wpfc#-4.0datagriddefaultbutton

WPF default button not working when datagrid row is selected


I have used a Datagrid and a button(btnAdd) in WPF.The button is default.I need to call btnAdd_Click(which uses the selected row of the Datagrid) when Enter key is pressed.

In other words i need to select a row & press Enter & do the work done by btnAdd_Click.

<Button  Name="btnAdd"  Click="btnAdd_Click" IsDefault="True" TabIndex="4" >Add to List</Button>   

Solution

  • you can get the PreviewKeyDown and mark e.Handeled = true

    dg = DataGrid

        protected override void OnInitialized(EventArgs e)
        {
            dg.PreviewKeyDown += new KeyEventHandler(dg_PreviewKeyDown);
            base.OnInitialized(e);
        }
    
        void dg_PreviewKeyDown(object sender, KeyEventArgs e)
        {
    
            if (Key.Enter == e.Key)
            {
                btnAdd_Click();
                e.Handled = true;
            }
        }