如何在列表框的末端创建一个“更多”按钮并处理它
本文关键字:更多 一个 按钮 处理 列表 创建 | 更新日期: 2023-09-27 18:10:44
我在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>
我的列表框添加了这个样式
Style="{StaticResource ListBoxMore}"
它是有效的,但问题是…
如何在代码隐藏中获得此按钮?我需要给这个按钮添加属性并处理点击,我怎么得到这个按钮?
一种常见的方法是创建一个自定义控件:
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.
}
}
}
注意在TemplatePartAttribute
和OnApplyTemplate
的覆盖中都使用了字符串PART_MoreButton。该属性告诉控件的使用者,您期望他们提供的任何ControlTemplate
必须具有类型为Button
的控件,名称为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>
当WPF为控件的每个实例膨胀模板时,将调用覆盖。此时,您可以访问按钮并注册事件处理程序等。希望这对你有帮助!