C# how to execute the markup event first?
I have this markupExtension Class
[MarkupExtensionReturnType(typeof(FrameworkElement))]
[ContentProperty("content")]
public class InsereSom : MarkupExtension
{
public InsereSom()
{ }
开发者_如何转开发 [ConstructorArgument("Ligado")]
public bool Ligado
{
get;
set;
}
[ConstructorArgument("Evento")]
public RoutedEvent Evento
{
get;
set;
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
IProvideValueTarget target = (IProvideValueTarget)serviceProvider.GetService(typeof(IProvideValueTarget));
FrameworkElement elemento = target.TargetObject as FrameworkElement;
RoutedEventHandler metodo = new RoutedEventHandler(EventoInsereSom);
elemento.AddHandler(Evento, metodo);
EventInfo eventInfo = elemento.GetType().GetEvent("Click");
FrameworkElement parentClass = (MainWindow)((Grid)elemento.Parent).Parent;
Delegate methodDelegate = Delegate.CreateDelegate(eventInfo.EventHandlerType, parentClass, "Button_Click");
eventInfo.RemoveEventHandler(elemento, methodDelegate);
eventInfo.AddEventHandler(elemento, methodDelegate);
return new System.Windows.Controls.Label();
}
public void EventoInsereSom(object sender, RoutedEventArgs e)
{
MessageBox.Show("Hello Extension Markup");
}
And this Xaml
<Button Width="80" Height="25" Click="Button_Click" Name="BtnTeste">
<Cei:InsereSom Ligado="True" Evento="Button.Click"/>
</Button>
And this code behind
public void Button_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Event code behind");
}
I'd like that my method in my markup class execute first than the method in the code behind.
I try to add and remove the EventHandler but for that I need the event name ("Button_Click"). But cant use it hard code.
are there any other way to to id?
Thanks.
I'd like that my method in my markup class execute first than the method in the code behind.
It's not possible, the order in which event handlers are called can only be controlled by the class that raises the event (the button in that case). It's like a newspaper: when you subscribe to it, you can't say "I want to receive my paper before my neighbor"...
However there is a way to have the markup extension detect the click before the code-behind: you can make it handle the PreviewClick
event (which is the tunnelling version of Click
)
精彩评论