问题
I'm fairly new to the world of Silverlight so please bear with me. I have created a custom pivot item control to be displayed in a pivot control. Now in this custom control there's a button. Now i could just add the click event handler to the button in the custom control's backing cs file and that would be ok. But is there a way for me to specify the event handler of the custom control's button during the declaration of the custom control? i.e. something like this in my pivot_page.xaml
<custom:myPivotItem background="..." height=".." width=".." click="myHandler"/>
where myHandler is declared in pivot_page.cs? Thanks
回答1:
You could expose a public event on your custom control that maps to the button's click event.
public event RoutedEventHandler Click
{
add { this.button.Click += value; }
remove { this.button.Click -= value; }
}
回答2:
Solved it by declaring a RoutedEventHandler in the custom controls cs file (myCustomPivotItem.cs).
public event RoutedEventHandler Click;
Then in onApplyTemplate I get access to the rectangle object with
Rectangle rect = this.GetTemplateChild("rectObject") as Rectangle;
rect.Tap += new EventHandler<GestureEventArgs>(RectView_Tap);
I then declared RectView_Tap in the same cs file (myCustomPivotItem.cs)
private void RectView_Tap(object sender, GestureEventArgs e)
{
if (Click != null)
Click(this, new RoutedEventArgs());
}
in my MainPage.xaml i declared the custom control like so
<controls:PivotItem x:Name="pivotitem2">
<view:myCustomePivotItem x:Name="custompivotItem2" Click="myHandler"/>
</controls:PivotItem>
and in MainPage.cs i declared myHandler...
void myHandler(object sender, RoutedEventArgs e)
{
//delegate operation
MessageBox.Show("Clicked!");
}
And it works as expected!! :) Hope it helps anyone who needs it.
来源:https://stackoverflow.com/questions/8846195/how-to-achieve-click-event-via-dependency-property-in-silverlight