I am writing a custom control in Silverlight and I am having issues getting my Button to click to the Generic.xaml file. This does not work:
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:ScrollableTabControl">
<Button Grid.Row="0" Grid.Column="0" x:Name="ScrollLeft" Click="scrollLeft"><</Button>
</ControlTemplate>
</Setter.Value>
"ScrollLeft" is in my C# file.
However this does not work either:
var b = this.G开发者_Go百科etTemplateChild("ScrollLeft");
Debug.Assert(b != null);
Because no matter what I do, b always comes back null. I feel like there should be an easy way to assign the click method to this button, so what am I doing wrong?
EDIT: This is the method from my C# file:
public void scrollLeft(object sender, RoutedEventArgs e)
{
//var scroller = Application.Current.Resources["TabScroller"] as ScrollViewer;
//scroller.LineLeft();
}
You have to override the OnApplyTemplate() on your custom control class (C# File).
Like this.
public override void OnApplyTemplate()
{
Button btn = GetTemplateChild("ScrollLeft") as Button;
Debug.Assert(btn != null);
}
Also, you have to make one more change in the control template in Generic.Xaml like below.
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:CustomControl1}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<Button Grid.Row="0" Grid.Column="0" x:Name="ScrollLeft"><</Button>
</Border>
</ControlTemplate>
</Setter.Value>
Note: I removed the Click event handler.
Although is it possible I recommend using Commands so the designer who replaces the template is free to pick other controls and events to bind the logic to.
精彩评论