自定义ListBox内容添加及点击按钮无显示问题求助
WPF自定义ListBox问题解决方案
问题1:如何向自定义ListBox中添加内容?
有三种常用实现方式:
- XAML直接声明项:在ListBox标签内直接添加
ListBoxItem,适合静态固定内容:
<ListBox x:Name="lsbResultaatTaal"> <ListBoxItem>中文</ListBoxItem> <ListBoxItem>English</ListBoxItem> </ListBox>
- 后台代码直接添加:通过ListBox的
Items集合动态添加数据,支持字符串或自定义实体:
// 添加字符串项 lsbResultaatTaal.Items.Add("中文"); lsbResultaatTaal.Items.Add("English"); // 自定义实体示例 public class Language { public string Name { get; set; } } // 添加实体项 lsbResultaatTaal.Items.Add(new Language { Name = "中文" });
- 绑定数据源(推荐):使用
ObservableCollection作为数据源,实现数据自动同步:
public ObservableCollection<Language> Languages { get; set; } = new ObservableCollection<Language>(); public MainWindow() { InitializeComponent(); DataContext = this; Languages.Add(new Language { Name = "中文" }); Languages.Add(new Language { Name = "English" }); }
对应XAML需修改ItemTemplate绑定实体属性:
<ListBox x:Name="lsbResultaatTaal" ItemsSource="{Binding Languages}"> <ListBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Name}"/> </DataTemplate> </ListBox.ItemTemplate> </ListBox>
问题2:自定义ControlTemplate后点击按钮无内容显示
核心问题是ControlTemplate使用了错误的控件:ListBox需要用ItemsPresenter渲染列表项,而非ContentPresenter(后者仅用于显示控件的Content属性,不处理Items集合)。修改后的ControlTemplate如下:
<ListBox.Template> <ControlTemplate TargetType="ListBox"> <Border Width="230" Height="450" CornerRadius="9" BorderThickness="1" BorderBrush="Black" Background="{TemplateBinding Background}"> <!-- 替换ContentPresenter为ItemsPresenter,添加ScrollViewer支持滚动 --> <ScrollViewer Padding="{TemplateBinding Padding}" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto"> <ItemsPresenter/> </ScrollViewer> </Border> </ControlTemplate> </ListBox.Template>
另外注意:你当前ItemTemplate中的{d:SampleData ItemCount=5}仅为设计时预览数据,运行时不会显示真实内容,需替换为绑定真实数据源的属性(如上述问题1中的{Binding Name})。
内容的提问来源于stack exchange,提问作者Elias
相关产品推荐
相关产品推荐

