How would I change the way the event handler works in an inherited class?
.net-4.0, c#
Solution
`PageChanged` is a field-like event. From outside the declaring class - even within a subclass - you can only use it to subscribe to and unsubscribe from the event.
The solution here would normally be to simply delegate to the base implementation of `OnPageChanged` conditionally:
public class LoopingPageView : PageView
{
protected override void OnPageChanged()
{
int pageIndex = Pages.IndexOf(ActivePage);
if (pageIndex > 0 && pageIndex < Pages.Count - 1)
{
base.OnPageChanged();
}
}
}
However, in this case you're trying to change the value which is passed to the handler as well. You can't do this with your current setup.
If you really need to do this (it seems odd to me, and violates the principle of least surprise - the subclass is acting significantly differently to the base class) you should probably make `OnPageChanged()` delegate to an overload which takes the page index (or a - `PageChangedEventArgs`) in which case your override of `OnPageChanged()` can call that with a different index. For example:
protected virtual void OnPageChanged()
{
OnPageChanged(new PageChangedEventArgs(Pages.IndexOf(activePage));
}
// Note: this doesn't need to be virtual.
protected void OnPageChanged(PageChangedEventArgs args)
{
// Null-safe event raising
var handler = PageChanged;
if (handler != null)
{
handler(this, args);
}
}
Then in the derived class:
protected override void OnPageChanged()
{
int pageIndex = Pages.IndexOf(ActivePage);
if (pageIndex > 0 && pageIndex < Pages.Count - 1)
{
base.OnPageChanged(new PageChangedEventArgs(pageIndex - 1));
}
}
Problem
I am working with a custom class and have an event handler to watch a property and only react in specific cases. Here is a snippet from the base class: ``` public class PageView { private UIView activePage; public List<UIView> Pages { get; set; } public delegate void PageChangedEventHandler(object sender, PageChangedEventArgs e); public event PageChangedEventHandler PageChanged; public UIView ActivePage { get { return activePage; } set { if (!activePage.Equals(value)) { activePage = value; OnPageChanged(); } } } protected virtual void OnPageChanged() { if (PageChanged != null) PageChanged(this, new PageChangedEventArgs(Pages.IndexOf(activePage))); } } ``` Here is what I am trying to do in the child class: ``` public class LoopingPageView : PageView { protected override void OnPageChanged() { if (PageChanged != null && Pages.IndexOf(ActivePage) > 0 && Pages.IndexOf(ActivePage) < Pages.Count - 1) PageChanged(this, Pages.IndexOf(ActivePage) - 1); } } ``` However, I get the message that PageChanged can only exist on the left side of a += or -= statement. What is the correct way to handle this case?