WPF ListBox ItemTemplatce DataTemplate Image

复制代码
//xaml
<Window x:Class="WpfApp152.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:WpfApp152"
        WindowState="Maximized"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <local:SizeConverter x:Key="sizeConverter"/>
    </Window.Resources>
    <Grid>
        <ListBox x:Name="lbx"                 
                 ItemsSource="{Binding ImgsCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Grid Height="{Binding ActualHeight,RelativeSource={RelativeSource Mode=FindAncestor,
                        AncestorType={x:Type Window}},Converter={StaticResource sizeConverter},
                        ConverterParameter=1}"
                        Width="{Binding ActualWidth,RelativeSource={RelativeSource Mode=FindAncestor,
                        AncestorType={x:Type Window}}}">
                        <Image Source="{Binding}"
                               HorizontalAlignment="Left"
                               VerticalAlignment="Top"/>
                    </Grid>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</Window>



//cs
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.Text;
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 WpfApp152
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        int idx = 0;
        string fontName = "Arial";
        string guidStr = "";
        int fontSize = 120;

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

        private ObservableCollection<ImageSource> imgsCollection;
        public ObservableCollection<ImageSource> ImgsCollection
        {
            get
            {
                return imgsCollection==null ? imgsCollection = new ObservableCollection<ImageSource>():imgsCollection;
            }
            set
            {
                if(value!=imgsCollection)
                {
                    imgsCollection = value;
                    OnPropertyChanged(nameof(ImgsCollection));
                }
            }
        }

        public MainWindow()
        {
            InitializeComponent();
            this.DataContext= this;
            Application.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException;
            this.Loaded += MainWindow_Loaded;
        }

        private void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            Console.WriteLine(e.ToString());
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            guidStr = $"{Guid.NewGuid().ToString("N")}";
            string str = $"{++idx}\n\n{StrWrap(guidStr, (int)this.ActualWidth-100)}";
            DisplayImageSource(str);
            System.Timers.Timer tmr = new System.Timers.Timer();
            tmr.Elapsed += Tmr_Elapsed;
            tmr.Interval = 1000;
            tmr.Start();
        }

        private void Tmr_Elapsed(object? sender, System.Timers.ElapsedEventArgs e)
        {
            guidStr = $"{Guid.NewGuid().ToString("N")}";            
            string str = $"{++idx}\n\n{StrWrap(guidStr,(int)this.ActualWidth-100)}";
            DisplayImageSource(str);
        }

        void DisplayImageSource(string str, string fontName = "Arial", int fontSize = 120)
        {
            try
            {
                Application.Current?.Dispatcher.BeginInvoke(new Action(() =>
                {
                    this.Title = guidStr;
                    ImageSource imgSource = ConvertTextAsImageSource(str, fontName, fontSize);
                    ImgsCollection.Add(imgSource);
                    ScrollIntoLastItem();
                }));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        ImageSource ConvertTextAsImageSource(string strText, string fontName = "Arial", int fontSize = 120)
        {
            DrawingVisual drawingVisual = new DrawingVisual();
            using (DrawingContext drawingContext = drawingVisual.RenderOpen())
            {
                FormattedText ft = new FormattedText(strText, CultureInfo.CurrentCulture,
                    FlowDirection.LeftToRight, new Typeface(fontName), fontSize, Brushes.Red, 1.25);
                drawingContext.DrawText(ft, new Point(0, 0));
            }
            RenderTargetBitmap renderTargetBmp = new RenderTargetBitmap((int)this.ActualWidth,
                   (int)this.ActualHeight,
                   96, 
                   96, 
                   PixelFormats.Default);
            renderTargetBmp.Render(drawingVisual);
            return renderTargetBmp;
        }

        string StrWrap(string str, int width,string fontName="Arial",int fontSize=120)
        {
            if(string.IsNullOrWhiteSpace(str))
            {
                return str;
            }
            char[] charArr= str.ToCharArray();
            StringBuilder builder = new StringBuilder();
            StringBuilder lineBuilder = new StringBuilder();
            foreach(char c in charArr)
            {
                if (GetStringWidth(lineBuilder.ToString()) >width)
                {
                    builder.AppendLine(lineBuilder.ToString());
                    lineBuilder.Clear();
                }
                lineBuilder.Append(c);
            }
            builder.AppendLine(lineBuilder.ToString());
            return builder.ToString();
        }

        int GetStringWidth(string str,string fontName="Arial",int fontSize=120)
        {
            FormattedText formattedText = new FormattedText(str,
                CultureInfo.CurrentCulture,
                FlowDirection.LeftToRight,
                new Typeface(fontName),
                fontSize,
                Brushes.Black,
                1.25);
            return (int)formattedText.Width;
        }

        void ScrollIntoLastItem()
        {
            lbx.ScrollIntoView(lbx.Items[lbx.Items.Count - 1]);
        }
        
    }

    public class SizeConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            double dValue = 0, paraValue = 0;
            if(Double.TryParse(value.ToString(), out dValue) && double.TryParse(parameter?.ToString(),out paraValue))
            {
                return dValue/paraValue;
            }
            return 0;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
复制代码

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @   FredGrit  阅读(3)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
历史上的今天:
2017-02-04 Linq
点击右上角即可分享
微信分享提示