A common approach is to create a custom control:
using System; using System.Windows; using System.Windows.Controls; namespace WpfApplication2 { [TemplatePart(Name=PartMoreButtonName, Type=typeof(Button))] public class MyListBox : ListBox { private const string PartMoreButtonName = "PART_MoreButton"; private Button _moreButton; public override void OnApplyTemplate() {
Note the use of the PART_MoreButton string in both TemplatePartAttribute and OnApplyTemplate overrides. This attribute tells consumers of your control that you expect that any ControlTemplate that they provide should have a Button control type named PART_MoreButton :
<StackPanel> <l:MyListBox> <l:MyListBox.Style> <Style TargetType="ListBox"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="ListBox"> <ScrollViewer x:Name="ScrollViewer"> <StackPanel> <ItemsPresenter/> <Button x:Name="PART_MoreButton" Content="More"></Button> </StackPanel> </ScrollViewer> </ControlTemplate> </Setter.Value> </Setter> </Style> </l:MyListBox.Style> </l:MyListBox> </StackPanel>
When WPF inflates a template for each instance of your control, an override is called. At this point you will have access to your button and you can register event handlers, etc. Hope this helps!
source share