Click here to Skip to main content
15,040,743 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi all ,

I am trying to override an event of the base class in the derived class.
Here what I am trying to achieve:

BaseClass ( wpf class having an Ok button as its component) is derived by a C# class which is not having xaml. Now I want to override the Click event in the derived class.

If I copy the method in the derived class it does not hit but hits the baseclass event only.

<pre>This is how the class structure is : 

Public partial class BaseDlg : Window  // this is a wpf class 
{
protected virtual void OkBtn_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("called from base");
        }
}

Now this class is derived in the SaveDlg class( a C# class) having no xaml file.

Public partial class SaveDlg : BaseDlg
{
protected virtual void OkBtn_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("called from derived");
        }

}  

<StackPanel Orientation="Horizontal">
                       <Button x:Name ="okBtn" Height="23" Margin="70,14,0,0"  VerticalAlignment="Top" HorizontalAlignment="Left" Width="76" Click="okBtn_Click" >OK</Button>

   </StackPanel>


Now this Click event is created in the BaseDlg.xaml/xaml.cs files. Now I created an instance of SaveDlg somewhere as below :

SaveDlg obj = new SaveDlg();
obj.ShowDialog();

This invokes a dialog with the changed titles and other stuff for SaveDlg . Now when I click on the Ok button on the dialog it takes the call to the BaseDlg okBtn_Clicked event instead of SaveDlg class overridden okBtn_Click event handler which I actually copied in this file.
So here's my question how can I achieve the calling of okBtn_Clicked from the derived class.

What I have tried:

I tried using virtual keyword in the base class but it didn't help.
Posted
Updated 16-Dec-20 2:06am
v2
Comments
Richard Deeming 16-Dec-20 3:52am
   
If you want someone to help you fix your code, you need to show us the code.

Click the green "Improve question" link and update your question to show the relevant parts of your code.

1 solution

To override a virtual member from the base class, the derived class needs to use the override modifier, not the virtual modifier.
virtual - C# Reference | Microsoft Docs[^]
C#
public partial class SaveDlg : BaseDlg
{
    protected override void OkBtn_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("called from derived");
    }
}  
   
Comments
Richard Deeming 16-Dec-20 12:18pm
   
Then you haven't declared the protected virtual method in your BaseDlg class that you showed in your question.
iampradeepsharma 16-Dec-20 12:34pm
   
Yes, it worked. Thanks Richard ! you made my day. Thanks again

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900