WPF自制文件、文字输入框

WPF自制文件、文字输入框

第一步加载资源

<Application x:Class="LinseerCopilot.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:LinseerCopilot"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/Images/Image.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <BitmapImage x:Key="Image.Close.Normal24" UriSource="pack://application:,,,/Images/Resources/ic_close_normal_24.png" />
    <BitmapImage x:Key="Image.Add" UriSource="pack://application:,,,/Images/Resources/add.jpg" />
    <BitmapImage x:Key="Image.AddSession" UriSource="pack://application:,,,/Images/Resources/add_session.png" />
    <BitmapImage x:Key="Image.Audio" UriSource="pack://application:,,,/Images/Resources/audio.jpg" />
    <BitmapImage x:Key="Image.Extend" UriSource="pack://application:,,,/Images/Resources/extend.png" />
    <BitmapImage x:Key="Image.LingXi" UriSource="pack://application:,,,/Images/Resources/lingxi.png" />
    <BitmapImage x:Key="Image.Send" UriSource="pack://application:,,,/Images/Resources/send.png" />
    <BitmapImage x:Key="Image.CloseSelect" UriSource="pack://application:,,,/Images/Resources/close_select.png" />  
</ResourceDictionary>

2 编写已选择文件Xaml

<UserControl x:Class="LinseerCopilot.Controls.SelectFile"
             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:easyStyles="clr-namespace:H3C.Windows.EasyStyles;assembly=H3C.Windows.EasyStyles"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800">
    <UserControl.Resources>
        <Style TargetType="Border" x:Key="BorderMouseOverStyle">
            <Setter Property="Background" Value="#ffffff" />
            <Setter Property="BorderBrush" Value="Gray" />
            <Setter Property="BorderThickness" Value="2" />
            <Setter Property="CornerRadius" Value="10" />
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="Background" Value="#e0e0e0" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </UserControl.Resources>
    <Border  Style="{StaticResource BorderMouseOverStyle}" Width="240" Height="60">
       <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="80" />
                <ColumnDefinition Width="160" />
            </Grid.ColumnDefinitions>
           <Image Grid.Column="0" Source="{Binding FileSource,Mode=OneWay,RelativeSource={RelativeSource AncestorType=UserControl}}" Width="48" Height="48" Stretch="UniformToFill" />
            <TextBlock Grid.Column="1" Text="{Binding FileName,Mode=OneWay,RelativeSource={RelativeSource AncestorType=UserControl}}" TextTrimming="WordEllipsis" 
                       Width="160" TextWrapping="NoWrap" FontSize="20" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="2,0" />
           <Button Grid.Column="0" Grid.ColumnSpan="2" easyStyles:ControlHelper.ImageSize="32" 
                   HorizontalAlignment="Right"
                   VerticalAlignment="Top"
                   Style="{StaticResource Style.Button.Image}" 
                   easyStyles:ControlHelper.ImageNormal="{StaticResource Image.CloseSelect}"
                   Margin="0,5,10,0" Click="CloseSelect_OnClick" />
        </Grid>
   </Border>
</UserControl>
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;

namespace LinseerCopilot.Controls
{
    /// <summary>
    /// SelectFile.xaml 的交互逻辑
    /// </summary>
    public partial class SelectFile : UserControl
    {
        public SelectFile()
        {
            InitializeComponent();
        }

        public static readonly DependencyProperty FileNameProperty = DependencyProperty.Register(nameof(FileName), typeof(string), typeof(SelectFile), new PropertyMetadata(null));
        /// <summary>
        /// 文件名称
        /// </summary>
        public string FileName
        {
            get => (string)GetValue(FileNameProperty);
            set => SetValue(FileNameProperty, value);
        }

        public static readonly DependencyProperty FileSourceProperty = DependencyProperty.Register(nameof(FileSource), typeof(BitmapImage), typeof(SelectFile), new PropertyMetadata(null));
        /// <summary>
        /// 文件源
        /// </summary>
        public BitmapImage FileSource
        {
            get => (BitmapImage)GetValue(FileSourceProperty);
            set => SetValue(FileSourceProperty, value);
        }

        /// <summary>
        /// 文件Id
        /// </summary>
        public string FileId { get; set; }

        public static readonly RoutedEvent OnCloseSelectEvent = EventManager.RegisterRoutedEvent(nameof(OnCloseSelect),
            RoutingStrategy.Bubble,
            typeof(RoutedEventHandler),
            typeof(SelectFile));
        /// <summary>
        ///添加新的会话
        /// </summary>
        public event RoutedEventHandler OnCloseSelect
        {
            add => AddHandler(OnCloseSelectEvent, value);
            remove => RemoveHandler(OnCloseSelectEvent, value);
        }

        /// <summary>
        /// 关闭选择
        /// </summary>
        private void CloseSelect_OnClick(object sender, RoutedEventArgs e)
        {
            RaiseEvent(new RoutedEventArgs(OnCloseSelectEvent, FileId));
        }
    }
}

### 3 输入框
```language
<UserControl x:Class="LinseerCopilot.Controls.Input"
             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:easyStyles="clr-namespace:H3C.Windows.EasyStyles;assembly=H3C.Windows.EasyStyles"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800">
    <UserControl.Resources>
        <Style TargetType="{x:Type ListBoxItem}" x:Key="Style.SlideListBoxItem">
            <Setter Property="FocusVisualStyle" Value="{x:Null}" />
            <Setter Property="Background" Value="Transparent" />
            <Setter Property="Margin" Value="5,0"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate  TargetType="{x:Type ListBoxItem}">
                        <ContentPresenter VerticalAlignment="Center" HorizontalAlignment="Stretch"/>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

        <ControlTemplate x:Key="Template.ListBox" TargetType="{x:Type ListBox}">
            <ScrollViewer  HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Disabled"
                           CanContentScroll="True" 
                           PanningMode="VerticalOnly" Margin="20,15,15,0">
                <StackPanel  IsItemsHost="True" Orientation="Horizontal"  HorizontalAlignment="Left"  FocusVisualStyle="{x:Null}" />
            </ScrollViewer>
        </ControlTemplate>

        <Style TargetType="{x:Type ListBox}" x:Key="Style.HiddenWhenEmpty">
            <Setter Property="Visibility" Value="Visible" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding FileList.Count, RelativeSource={RelativeSource AncestorType=UserControl}}" Value="0">
                    <Setter Property="Visibility" Value="Collapsed" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </UserControl.Resources>
    <Border Background="#FFFFFF" CornerRadius="60">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>

            <ListBox x:Name="SessionItemsControl"
                     Grid.Row="0"
                     Height="80"
                     Background="Transparent" 
                     SelectionMode="Single"
                     BorderThickness="0"  
                     ItemsSource="{Binding FileList,Mode=OneWay,RelativeSource={RelativeSource AncestorType=UserControl}}"
                     SelectedItem="{Binding SelectedItem,Mode=OneWay,RelativeSource={RelativeSource AncestorType=UserControl}}"
                     Template="{StaticResource Template.ListBox}"
                     ItemContainerStyle="{StaticResource Style.SlideListBoxItem}"
                     Style="{StaticResource Style.HiddenWhenEmpty}"
                     ManipulationBoundaryFeedback="UIElement_OnManipulationBoundaryFeedback">
            </ListBox>
            <Grid Grid.Row="1" Height="120">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="80"/>
                    <ColumnDefinition Width="80"/>
                    <ColumnDefinition Width="80"/>
                </Grid.ColumnDefinitions>
                <TextBox Grid.Column="0" BorderThickness="0" Background="Transparent" Margin="20,2,0,15" FontSize="28" VerticalContentAlignment="Center"
                         Text="测试输入..."  AcceptsReturn="True" TextWrapping="WrapWithOverflow"  VerticalScrollBarVisibility="Auto"/>
                <Button Grid.Column="1" easyStyles:ControlHelper.ImageSize="44"  Style="{StaticResource Style.Button.Image}" 
                        easyStyles:ControlHelper.ImageNormal="{StaticResource Image.Add}"
                        Margin="10,5" Click="Select_OnClick" />
                <Button Grid.Column="2" easyStyles:ControlHelper.ImageSize="44"  Style="{StaticResource Style.Button.Image}" 
                        easyStyles:ControlHelper.ImageNormal="{StaticResource Image.Audio}"
                        Margin="10,5" Click="Audio_OnClick" />
                <Button Grid.Column="3" easyStyles:ControlHelper.ImageSize="44"  Style="{StaticResource Style.Button.Image}" 
                        easyStyles:ControlHelper.ImageNormal="{StaticResource Image.Send}"
                        Margin="10,5" Click="Send_OnClick" />
            </Grid>
        </Grid>
    </Border>
</UserControl>
using System;
using Microsoft.Win32;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;

namespace LinseerCopilot.Controls
{
    /// <summary>
    /// Input.xaml 的交互逻辑
    /// </summary>
    public partial class Input : UserControl
    {
        public Input()
        {
            InitializeComponent();
            FileList = new ObservableCollection<SelectFile>();
            var selectFile = new SelectFile
            {
                FileId = Guid.NewGuid().ToString(),
                FileName = "万马奔腾",
                FileSource = new System.Windows.Media.Imaging.BitmapImage(new System.Uri("pack://application:,,,/LinseerCopilot;component/Images/Resources/lingxi.png"))
            };
            selectFile.OnCloseSelect += (sender, e) =>
            {
                FileList.Remove(selectFile);
            };
            var selectFile1 = new SelectFile
            {
                FileId = Guid.NewGuid().ToString(),
                FileName = "亿马奔腾",
                FileSource = new System.Windows.Media.Imaging.BitmapImage(new System.Uri("pack://application:,,,/LinseerCopilot;component/Images/Resources/lingxi.png"))
            };
            selectFile1.OnCloseSelect += (sender, e) =>
            {
                FileList.Remove(selectFile1);
            };
            FileList.Add(selectFile);
            FileList.Add(selectFile1);
        }

        public static readonly DependencyProperty FileListProperty = DependencyProperty.Register(nameof(FileList), typeof(ObservableCollection<SelectFile>), typeof(Input), new PropertyMetadata(null));
        /// <summary>
        /// 文件源
        /// </summary>
        public ObservableCollection<SelectFile> FileList
        {
            get => (ObservableCollection<SelectFile>)GetValue(FileListProperty);
            set => SetValue(FileListProperty, value);
        }

        public static readonly DependencyProperty SelectedItemProperty = DependencyProperty.Register(nameof(SelectedItem), typeof(SelectFile), typeof(Input), new PropertyMetadata(null));
        /// <summary>
        /// 文件源
        /// </summary>
        public SelectFile SelectedItem
        {
            get => (SelectFile)GetValue(SelectedItemProperty);
            set => SetValue(SelectedItemProperty, value);
        }

        /// <summary>
        /// 语音
        /// </summary>
        private void Audio_OnClick(object sender, RoutedEventArgs e)
        {

        }

        /// <summary>
        /// 打开文件对话框,选择文件
        /// </summary>
        private void Select_OnClick(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Multiselect = true;
            // 设置对话框的过滤器以限制用户可以选择的文件类型
            openFileDialog.Filter = "所有文件 (*.*)|*.*|文本文件 (*.txt)|*.txt|图像文件 (*.jpg;*.jpeg;*.png)|*.jpg;*.jpeg;*.png";

            // 如果用户在对话框中选择了文件,并点击了“打开”按钮
            if (openFileDialog.ShowDialog() == true)
            {
                // 获取用户选择的文件路径
                string selectedFilePath = openFileDialog.FileName;
                var selectFile = new SelectFile
                {
                    FileId = Guid.NewGuid().ToString(),
                    FileName = "万马奔腾",
                    FileSource = new System.Windows.Media.Imaging.BitmapImage(new System.Uri("pack://application:,,,/LinseerCopilot;component/Images/Resources/lingxi.png"))
                };
                selectFile.OnCloseSelect += (s, e1) =>
                {
                    FileList.Remove(selectFile);
                };
                FileList.Add(selectFile);
            }
        }

        /// <summary>
        /// 发送
        /// </summary>
        private void Send_OnClick(object sender, RoutedEventArgs e)
        {

        }

        private void UIElement_OnManipulationBoundaryFeedback(object sender, System.Windows.Input.ManipulationBoundaryFeedbackEventArgs e)
        {
            e.Handled = true;
        }
    }
}

演示效果

image.png

image.png

posted on 2026-07-20 10:40  TanZhiWei  阅读(11)  评论(0)    收藏  举报