WPF ListBox ListBox use UserControl

//usercontrol xaml
<UserControl x:Class="WpfApp379.ImgTbk"
             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:WpfApp379"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800">
    <Grid>
        <Image Source="{Binding UCImgUrl,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                   Width="{Binding Path=ActualWidth,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Window}}}"
                   Height="{Binding Path=ActualHeight,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Window}}}"/>
        <TextBlock Text="{Binding UCTbkStr,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" 
                   FontSize="100" VerticalAlignment="Center" HorizontalAlignment="Center"/>
    </Grid>
</UserControl>


//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 WpfApp379
{
    /// <summary>
    /// Interaction logic for ImgTbk.xaml
    /// </summary>
    public partial class ImgTbk : UserControl
    {
        public ImgTbk()
        {
            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(ImgTbk), new PropertyMetadata(""));




        public string UCTbkStr
        {
            get { return (string)GetValue(UCTbkStrProperty); }
            set { SetValue(UCTbkStrProperty, value); }
        }

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




    }
}




//
 <ListBox.ItemTemplate>
     <DataTemplate>
         <Grid>
             <local:ImgTbk UCImgUrl="{Binding DataContext.ImgUrl,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ListBoxItem}}}" 
                           UCTbkStr="{Binding DataContext.Name,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ListBoxItem}}}"/>
         </Grid>
     </DataTemplate>
 </ListBox.ItemTemplate>

 

 

//usercontrol xaml

<UserControl x:Class="WpfApp379.ImgTbk"
             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:WpfApp379"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800">
    <Grid>
        <Image Source="{Binding UCImgUrl,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                   Width="{Binding Path=ActualWidth,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Window}}}"
                   Height="{Binding Path=ActualHeight,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Window}}}"/>
        <TextBlock Text="{Binding UCTbkStr,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" 
                   FontSize="100" VerticalAlignment="Center" HorizontalAlignment="Center"/>
    </Grid>
</UserControl>



//usercontrol.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 WpfApp379
{
    /// <summary>
    /// Interaction logic for ImgTbk.xaml
    /// </summary>
    public partial class ImgTbk : UserControl
    {
        public ImgTbk()
        {
            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(ImgTbk), new PropertyMetadata(""));




        public string UCTbkStr
        {
            get { return (string)GetValue(UCTbkStrProperty); }
            set { SetValue(UCTbkStrProperty, value); }
        }

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




    }
}


//xaml
<Window x:Class="WpfApp379.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:WpfApp379" 
        mc:Ignorable="d" WindowState="Maximized"
        Title="MainWindow" Height="450" Width="800">
    <Window.DataContext>
        <local:BookVM/>
    </Window.DataContext>
    <Grid>
        <!--<ListBox xmlns:sys="clr-namespace:System;assembly=mscorlib">
            <Button>Button</Button>
            <Expander Header="Expander"/>
            <sys:DateTime>1/1/2012</sys:DateTime>
            <sys:DateTime>1/2/2012</sys:DateTime>
            <sys:DateTime>1/3/2012</sys:DateTime>
        </ListBox>-->
        <Grid.RowDefinitions>
            <RowDefinition Height="50"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <ToolBar Grid.Row="0">
            <Button Content="Load" Command="{Binding LoadCmd}" Width="100"/>
        </ToolBar>
        <ListBox x:Name="lbx" Grid.Row="1" BorderBrush="Blue" BorderThickness="5"
                 VirtualizingPanel.CacheLength="100" 
                 VirtualizingPanel.CacheLengthUnit="Item"
                 VirtualizingPanel.IsContainerVirtualizable="True"
                 VirtualizingPanel.IsVirtualizing="True"
                 VirtualizingPanel.VirtualizationMode="Recycling"
                 ItemsSource="{Binding BooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">
            <!--<ListBox.ContextMenu>
                <ContextMenu>
                    <MenuItem Header="Export NewtonSoftJson"  
                              FontSize="50" 
                              Foreground="Red"
                              Command="{Binding ExportNewtonJsonCmd}"
                              CommandParameter="{Binding RelativeSource={RelativeSource 
                              Mode=FindAncestor,AncestorType={x:Type ContextMenu}},Path=PlacementTarget}"/>
                    <MenuItem Header="Export BinaryFormatter"
                              FontSize="50"
                              Foreground="Red"
                              Command="{Binding ExportBinaryFormatterCmd}"
                              CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor,
                        AncestorType={x:Type ContextMenu}},Path=PlacementTarget}"/>
                </ContextMenu>
            </ListBox.ContextMenu>-->
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <local:ImgTbk UCImgUrl="{Binding DataContext.ImgUrl,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ListBoxItem}}}" 
                                      UCTbkStr="{Binding DataContext.Name,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ListBoxItem}}}"/>
                    </Grid>
                </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;
using Microsoft.Win32;
using Newtonsoft.Json;
using System.Runtime.Serialization.Formatters.Binary;

namespace WpfApp379
{
    /// <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> booksCollection;
        public ObservableCollection<Book> BooksCollection
        {
            get
            {
                return booksCollection;
            }
            set
            {
                if (value != booksCollection)
                {
                    booksCollection = value;
                    OnPropertyChanged(nameof(BooksCollection));
                }
            }
        }


        public BookVM()
        {
            InitCmds();
            InitData();
        }

        public DelCmd LoadCmd { get; set; }

        public DelCmd ExportNewtonJsonCmd { get; set; }
        public DelCmd ExportBinaryFormatterCmd { get; set; }
        private void InitCmds()
        {
            LoadCmd = new DelCmd(LoadCmdExecuted);
            ExportNewtonJsonCmd = new DelCmd(ExportNewtonJsonCmdExecuted);
            ExportBinaryFormatterCmd = new DelCmd(ExportBinaryFormatterCmdExecuted);
        }

        private void ExportBinaryFormatterCmdExecuted(object obj)
        {
            var lbx = obj as ListBox;
            if (lbx != null)
            {
                var items = lbx.Items.Cast<Book>()?.ToList();
                if (items != null && items.Any())
                {
                    SaveFileDialog dialog = new SaveFileDialog();
                    dialog.Filter = "All Files|*.*|Json Files|*.json";
                    dialog.FileName = $"Bin{DateTime.Now.ToString("yyyyMMddHHmmssffff")}_{Guid.NewGuid().ToString("N")}.bin";
                    if (dialog.ShowDialog() == true)
                    {
                        using (FileStream fs = new FileStream(dialog.FileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                        {
                            BinaryFormatter binFormatter = new BinaryFormatter();
                            binFormatter.Serialize(fs, items);
                        }
                        MessageBox.Show($"Binary Serialized in {dialog.FileName}", "Binary Serialize", MessageBoxButton.OK);
                    }
                }
            }
        }

        private void ExportNewtonJsonCmdExecuted(object obj)
        {
            var lbx = obj as ListBox;
            if(lbx!=null)
            {
                var items = lbx.Items.Cast<Book>()?.ToList();
                if(items!=null && items.Any())
                {
                    SaveFileDialog dialog = new SaveFileDialog();
                    dialog.Filter = "All Files|*.*|Json Files|*.json";
                    dialog.FileName = $"Json{DateTime.Now.ToString("yyyyMMddHHmmssffff")}_{Guid.NewGuid().ToString("N")}.json";
                    if(dialog.ShowDialog()==true)
                    {
                        string jsonStr=JsonConvert.SerializeObject(items,Formatting.Indented);
                        File.AppendAllText(dialog.FileName, jsonStr);
                        MessageBox.Show($"Saved in {dialog.FileName}", "Saved Json", MessageBoxButton.OK);
                    }
                }
            }
        }

        private void LoadCmdExecuted(object obj)
        {
            InitData(); 
        }

        private void InitData()
        {
            var imgsList = Directory.GetFiles("../../Images");
            if (imgsList != null && imgsList.Count() > 0)
            {
                int imgsCount = imgsList.Count();
                BooksCollection = new ObservableCollection<Book>();
                for (int i = 0; i < 1000000; i++)
                {
                    BooksCollection.Add(new Book()
                    {
                        Id = i + 1,
                        Name = $"Name_{i + 1}",
                        Title = $"Title_{i + 1}",
                        Topic = $"Topic_{i + 1}",
                        ImgUrl = imgsList[i % imgsCount]
                    });
                }
            }
        }
    }

    public class DelCmd : ICommand
    {
        public event EventHandler CanExecuteChanged
        {
            add
            {
                CommandManager.RequerySuggested += value;
            }
            remove
            {
                CommandManager.RequerySuggested -= value;
            }
        }

        private Action<object> execute;
        private Predicate<object> canExecute;

        public DelCmd(Action<object> executeValue, Predicate<object> canExecuteValue)
        {
            execute = executeValue;
            canExecute = canExecuteValue;
        }

        public DelCmd(Action<object> executeValue) : this(executeValue, null)
        {
        }

        public bool CanExecute(object parameter)
        {
            if (canExecute == null)
            {
                return true;
            }
            return canExecute(parameter);
        }

        public void Execute(object parameter)
        {
            execute(parameter);
        }
    }


    [Serializable]
    public class Book
    {
        public int Id { get; set; }

        public string ImgUrl { get; set; }
        public string Name { get; set; }

        public string Title { get; set; }

        public string Topic { get; set; }
    }
}

 

posted @ 2024-09-18 21:35  FredGrit  阅读(9)  评论(0编辑  收藏  举报