首页 > 其他分享 >WPF ListBox ListBox use UserControl

WPF ListBox ListBox use UserControl

时间:2024-09-18 21:35:24浏览次数:9  
标签:use string Windows System new using WPF ListBox public

//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; }
    }
}

 

标签:use,string,Windows,System,new,using,WPF,ListBox,public
From: https://www.cnblogs.com/Fred1987/p/18419372

相关文章

  • WPF Expander ExpandDirection Left,Right,Up,Down
    //xaml<Windowx:Class="WpfApp378.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.mi......
  • WPF WebBrowser suppress script errors
    ScriptError,Anerrorhasoccuredinthescriptonthispage.Doyouwanttocontinuerunningscriptsonthispage?   //xaml<Windowx:Class="WpfApp378.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/present......
  • wpf简单自定义控件
    用户控件(UserControl)和自定义控件(CustomControl)的区别:UserControl:将多个WPF控件(例如:TextBox,TextBlock,Button)进行组合成一个可复用的控件组;由XAML和CodeBehind代码组成;不支持样式/模板重写;CustomControl自定义控件,扩展自一个已经存在的控件,并添加新的功能/特性;由C......
  • WPF CheckBox ToolTip Image
    <Windowx:Class="WpfApp377.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft......
  • WPF RadioButton GroupName
    <Windowx:Class="WpfApp375.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft......
  • zblog安装时出现您在zb_users/c_option.php内配置、或刚才填写的的 MySQL 连接信息是
    当你在安装Z-BlogPHP时遇到“您在 zb_users/c_option.php 内配置、或刚才填写的MySQL连接信息是否正确?”的提示时,这通常意味着数据库连接配置存在问题。以下是详细的排查和解决步骤:1.检查数据库连接配置首先,确保数据库连接配置正确。你需要检查以下几个方面:步骤1:查看......
  • [Clickhouse] Clickhouse 函数 : 数据类型转换
    0引言如无特殊说明,ck版本为21.3.4.251数据类型的支持情况查看当前受支持的数据类型select*fromsystem.data_type_families--selectname,case_insensitive,alias_tofromsystem.data_type_families;outputname|case_insensitive......
  • [PortSwigger] Lab: Finding and exploiting an unused API endpoint
    登入,加入Lightweightl33tLeatherJacket到購物車,結帳發現是錢不夠看前端jshttps://0a63004a0420062c80b83ad30022000c.web-security-academy.net/resources/js/api/productPrice.js會去拿product的價格找到api改成post,發現product有個patch可以用改成patch,提示con......
  • ClickHouse-Kafka Engine 正确的使用方式
    Kafka是大数据领域非常流行的一款分布式消息中间件,是实时计算中必不可少的一环,同时一款OLAP系统能否对接Kafka也算是考量是否具备流批一体的衡量指标之一。ClickHouse的Kafka表引擎能够直接与Kafka系统对接,进而订阅Kafka中的Topic并实时接受消息数据。众所周......
  • WPF LiveChart 图表详解
    引用LiveChart.Wpf在使用的界面当中引用LiveChart.Wpf的类库xmlns:lvc="clr-namespace:LiveCharts.Wpf;assembly=LiveCharts.Wpf"以直方图、折线图为例,都属于CartesianChart下的一种Series类型,例如折线图,如下:<lvc:CartesianChart><lvc:CartesianCh......