WPF ListBox ListBox.ItemTemplate DataTemplate Custom UserControl

FredGrit發表於2024-09-21
   <ListBox.ItemTemplate>
      <DataTemplate>
          <local:ImageTbk UCImgUrl="{Binding DataContext.ImgUrl,
              RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=ListBoxItem}}"
                          UCName="{Binding DataContext.Name,RelativeSource={RelativeSource 
              Mode=FindAncestor,AncestorType=ListBoxItem}}"
                          Height="800" Width="500"/>                   
      </DataTemplate>
  </ListBox.ItemTemplate>

//usercontrol.xaml
<UserControl x:Class="WpfApp388.ImageTbk"
             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" 
             xmlns:local="clr-namespace:WpfApp388"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800">
    <Grid>
        <Image Source="{Binding UCImgUrl,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                   />
        <TextBlock Text="{Binding UCName,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                   VerticalAlignment="Center"
                   HorizontalAlignment="Center"
                   FontSize="100"
                   Foreground="Red"/>
    </Grid>
</UserControl>


//usercontrol.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApp388
{
    /// <summary>
    /// Interaction logic for ImageTbk.xaml
    /// </summary>
    public partial class ImageTbk : UserControl
    {
        public ImageTbk()
        {
            InitializeComponent();
            this.DataContext = this;
        }



        public string UCImgUrl
        {
            get { return (string)GetValue(UCImgUrlProperty); }
            set { SetValue(UCImgUrlProperty, value); }
        }

        // Using a DependencyProperty as the backing store for UCImgUrl.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty UCImgUrlProperty =
            DependencyProperty.Register("UCImgUrl", typeof(string), 
                typeof(ImageTbk), new PropertyMetadata(""));




        public string UCName
        {
            get { return (string)GetValue(UCNameProperty); }
            set { SetValue(UCNameProperty, value); }
        }

        // Using a DependencyProperty as the backing store for UCName.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty UCNameProperty =
            DependencyProperty.Register("UCName", typeof(string), 
                typeof(ImageTbk), new PropertyMetadata(""));




    }
}



//xaml
<Window x:Class="WpfApp388.MainWindow"
        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:WpfApp388"
        mc:Ignorable="d"
        WindowState="Maximized"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <local:BookData x:Key="booksData"/>
    </Window.Resources>
    <Grid>
        <ListBox ItemsSource="{StaticResource booksData}"
        VirtualizingPanel.IsContainerVirtualizable="True"
                 VirtualizingPanel.IsVirtualizing="True"
                 VirtualizingPanel.CacheLength="100"
                 VirtualizingPanel.CacheLengthUnit="Item"
                 >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <local:ImageTbk UCImgUrl="{Binding DataContext.ImgUrl,
                        RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=ListBoxItem}}"
                                    UCName="{Binding DataContext.Name,RelativeSource={RelativeSource 
                        Mode=FindAncestor,AncestorType=ListBoxItem}}"
                                    Height="500" Width="500"/>                   
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</Window>


//xaml.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;

namespace WpfApp388
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }

    public class BookVM : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string propertyName)
        {
            var handler = PropertyChanged;
            if(handler!=null)
            {
                handler?.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        private ObservableCollection<Book> books;
        public ObservableCollection<Book> BooksCollection
        {
            get
            {
                return books;
            }
            set
            {
                if(books!=value)
                {
                    books = value;
                    OnPropertyChanged(nameof(BooksCollection));
                }
            }
        }
    }

    public class BookData:List<Book>
    {
        public BookData()
        {
            var imgsList = Directory.GetFiles(@"../../Images");
            if(imgsList!=null && imgsList.Any())
            {
                int imgsCount = imgsList.Count();
                for(int i=0;i<100000;i++)
                {
                    this.Add(new Book()
                    {
                        Id=i+1,
                        Name=$"Name_{i+1}",
                        Title=$"Title_{i+1}",
                        Topic=$"Topic_{i+1}",
                        ImgUrl = imgsList[i%imgsCount]
                    });
                }
            }
        }
    }

    public class Book
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public string Title { get; set; }

        public string Topic { get; set; }

        public string ImgUrl { get; set; }
    }
}

相關文章