C# 如何覆盖我的自定义按钮';不指定页面变量的事件
我创建了一个C# 如何覆盖我的自定义按钮';不指定页面变量的事件,c#,C#,我创建了一个CustomButton,继承自Button类。然后我创建了一些事件,比如GotFocus,LostFocus,等等 public sealed class CustomButton : Button { public CustomButton() { this.DefaultStyleKey = typeof(CustomButton); } protected override void OnApplyTemplate()
CustomButton
,继承自Button
类。然后我创建了一些事件,比如GotFocus
,LostFocus
,等等
public sealed class CustomButton : Button
{
public CustomButton()
{
this.DefaultStyleKey = typeof(CustomButton);
}
protected override void OnApplyTemplate()
{
this.GotFocus += CustomButton_GotFocus;
this.LostFocus += CustomButton_LostFocus;
base.OnApplyTemplate();
}
private void CustomButton_LostFocus(object sender, RoutedEventArgs e)
{
//some common behavior code
}
private void CustomButton_GotFocus(object sender, RoutedEventArgs e)
{
//some common behavior code
}
}
然后我在一些页面中使用了这个CustomButton
。但在某些指定页面中,我不希望CustomButton
执行GotFocus
,LostFocus
事件
那么,如何在指定页面中覆盖这些事件呢
我尝试在指定的页面中添加GotFocus
,LostFocus
事件,但它最终将在CustomButton
中运行公共代码行为。您可以通过迭代页面控件从CustomButton中“删除”事件:
foreach(var cb in this.Controls.OfType<CustomButton>())
{
cb.GotFocus -= CustomButton.GotFocus;
cb.LostFocus -= CustomButton.LostFocus;
}
foreach(this.Controls.OfType()中的var cb)
{
cb.GotFocus-=CustomButton.GotFocus;
cb.LostFocus-=CustomButton.LostFocus;
}
我相信这应该是可行的。对于需求,您可以创建一个
dependencProperty
来控制GotFocus
或LostFocus
事件是否可以执行
例如:
public class CustomButton : Button
{
public CustomButton()
{
this.DefaultStyleKey = typeof(Button);
Current = this;
}
private static CustomButton Current;
protected override void OnApplyTemplate()
{
base.OnApplyTemplate();
}
public bool EnableDetected
{
get { return (bool)GetValue(EnableDetectedProperty); }
set { SetValue(EnableDetectedProperty, value); }
}
// Using a DependencyProperty as the backing store for EnableDetected. This enables animation, styling, binding, etc...
public static readonly DependencyProperty EnableDetectedProperty =
DependencyProperty.Register("EnableDetected", typeof(bool), typeof(CustomButton), new PropertyMetadata(0, new PropertyChangedCallback(OnValueChanged)));
private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if ((bool)e.NewValue == true)
{
Current.GettingFocus += Current_GettingFocus;
}
else
{
Current.GettingFocus -= Current_GettingFocus;
}
}
private static void Current_GettingFocus(UIElement sender, GettingFocusEventArgs args)
{
}
}
用法
<local:CustomButton Content="Btn" EnableDetected="true" />
您可以创建一个属性UseBaseClass
并执行类似于if(UseBaseClass)base.LostFocus()的操作代码>你的意思是我把代码放在我指定的页面中?编译器无法识别CustomButton\u GotFocus
。是的,我的错是,它应该是一个点