How to make the "Advanced" button at the end of the list and process it?

I added this resource on App.xaml

 <Style x:Key="ListBoxMore" TargetType="ListBox"> <Setter Property="Background" Value="Transparent"/> <Setter Property="Foreground" Value="{StaticResource PhoneForegroundBrush}"/> <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled"/> <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto"/> <Setter Property="BorderThickness" Value="0"/> <Setter Property="BorderBrush" Value="Transparent"/> <Setter Property="Padding" Value="0"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="ListBox"> <ScrollViewer x:Name="ScrollViewer" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Foreground="{TemplateBinding Foreground}" Padding="{TemplateBinding Padding}"> <StackPanel> <ItemsPresenter/> <Button Content="More" Name="moreButton"></Button> </StackPanel> </ScrollViewer> </ControlTemplate> </Setter.Value> </Setter> </Style> 

And my list adds this style

 Style="{StaticResource ListBoxMore}" 

And it works, but the question is ...

How can I get this button in code? I need to add properties to this button and handle the click, how do I get this button?

+2
source share
1 answer

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() { // unhook any handlers from _moreButton to prevent a memory leak _moreButton = GetTemplateChild(PartMoreButtonName) as Button; // do stuff with _moreButton, register handlers, etc. } } } 

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!

+3
source

Source: https://habr.com/ru/post/891366/


All Articles