WPF用户控件批量数据绑定

author: JimStone
date: 2015/9/17 6:29

用户控件(UserControl2.xaml)

<UserControl x:Class="WpfApplication1.UserControl2"
             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="52" d:DesignWidth="337" Height="52">
    <Grid>
        <Button Content="{Binding Name}" Margin="10,10,10,0" Height="32" VerticalAlignment="Top"/>
    </Grid>
</UserControl>

主界面(MainWindow.xaml)

<Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfApplication1" xmlns:Properties="clr-namespace:WpfApplication1.Properties" mc:Ignorable="d" x:Class="WpfApplication1.MainWindow"
        Title="MainWindow" Height="453" Width="592" Loaded="Window_Loaded">
    <Grid Margin="0,0,2,0">
        <ItemsControl x:Name="ListItems" ItemsSource="{Binding}">
            <!-- 数据(批量)显示模板(DataTemplate指单个) -->
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <local:UserControl2 />
                </DataTemplate>
            </ItemsControl.ItemTemplate>
            <!-- 面板显示模板 -->
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Background="#FFA5F7FF">
                    </StackPanel>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
        </ItemsControl>
    </Grid>
</Window>

主界面代码(MainWindow.xaml.cs)


    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        public class User
        {
            public string Name
            {
                get;
                set;
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            BindingList<User> ul = new BindingList<User> {
                new User { Name = "Boy" },
                new User { Name = "Girl" },
                new User { Name = "JimStone" }
            };
            this.ListItems.ItemsSource = ul;
        }
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容