using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using Microsoft.Win32; namespace AIStudio.Wpf.Mind.Controls { [TemplatePart(Name = PART_OpenButton, Type = typeof(Button))] public class OpenFileTextBox : TextBox { private const string PART_OpenButton = "PART_OpenButton"; private Button _openButton; static OpenFileTextBox() { DefaultStyleKeyProperty.OverrideMetadata(typeof(OpenFileTextBox), new FrameworkPropertyMetadata(typeof(OpenFileTextBox))); } /// Identifies the dependency property. public static readonly DependencyProperty FilterProperty = DependencyProperty.Register(nameof(Filter), typeof(string), typeof(OpenFileTextBox), new UIPropertyMetadata("图像文件(*.bmp, *.jpg)|*.bmp;*.jpg|所有文件(*.*)|*.*")); /// /// Whether or not the "popup" menu for this control is currently open /// public string Filter { get => (string)this.GetValue(FilterProperty); set => this.SetValue(FilterProperty, (string)value); } public override void OnApplyTemplate() { base.OnApplyTemplate(); if (_openButton != null) { _openButton.Click -= _openButton_Click; } _openButton = this.Template.FindName(PART_OpenButton, this) as Button; if (_openButton != null) { _openButton.Click += _openButton_Click; } } private void _openButton_Click(object sender, RoutedEventArgs e) { OpenFileDialog fd = new OpenFileDialog(); fd.Title = "请选择文件"; fd.Filter = Filter; fd.FileName = Text?.Trim(); if (fd.ShowDialog() == true) { SetValue(TextProperty, fd.FileName); } //this.Focus(); } } }