You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WPF中创建带参数的ListView模板及自定义用户控件

实现可绑定ItemsSource的自定义StudentView控件

1. 创建StudentView用户控件的XAML

在WPF项目中添加新用户控件并命名为StudentView,XAML代码如下:

<UserControl x:Class="YourNamespace.StudentView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800">
    <ListView ItemsSource="{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=StudentItems}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Name}"/>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</UserControl>

2. 添加后台依赖属性

打开StudentView.xaml.cs,添加支持绑定的依赖属性:

using System.Windows;
using System.Windows.Controls;

namespace YourNamespace
{
    public partial class StudentView : UserControl
    {
        public static readonly DependencyProperty StudentItemsProperty =
            DependencyProperty.Register("StudentItems", typeof(object), typeof(StudentView), new PropertyMetadata(null));

        public object StudentItems
        {
            get { return GetValue(StudentItemsProperty); }
            set { SetValue(StudentItemsProperty, value); }
        }

        public StudentView()
        {
            InitializeComponent();
        }
    }
}

3. 在主窗口中使用StudentView

主窗口XAML里先引入自定义控件命名空间,再绑定不同数据源:

<Window x:Class="YourNamespace.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:YourNamespace"
        Title="MainWindow" Height="450" Width="800">
    <StackPanel>
        <local:StudentView StudentItems="{Binding Student1}"/>
        <local:StudentView StudentItems="{Binding Student2}"/>
        <local:StudentView StudentItems="{Binding Student3}"/>
    </StackPanel>
</Window>

关键说明

  • 必须用依赖属性才能支持WPF数据绑定,普通CLR属性无法实现响应式更新。
  • XAML中通过RelativeSource绑定到用户控件自身的StudentItems属性,确保数据源正确传递到内部ListView。
  • 主窗口ViewModel需包含Student1、Student2、Student3三个可绑定集合属性(建议用ObservableCollection<Student>类型)。

内容的提问来源于stack exchange,提问作者Jtastic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 15:55:33