自定义控件:类似于浏览路径弹出窗体

如图:点击浏览可弹出选择文件对话框,显示文件路径

1.在项目中添加新项,选择天加一个控件UserControl1.xaml,取名FileInputBox

在用户控件添加按钮和文本框,XAML代码如下:

<Button x:Name="theButton" DockPanel.Dock="Right" Click="theButton_Click">浏览...</Button>
<TextBox x:Name="theTextBox" MinWidth="{Binding ActualWidth, ElementName=theButton}" Text="{Binding FileName, ElementName=root}" />

2.用户控件cs代码如下:

   public partial class FileInputBox : UserControl
    {
        public FileInputBox()
        {
            InitializeComponent();
            theTextBox.TextChanged += new TextChangedEventHandler(OnTextChanged);
        }

        private void theButton_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog d = new OpenFileDialog();
            if (d.ShowDialog() == true) // Result could be true, false, or null
                this.FileName = d.FileName;
        }
        
        private void OnTextChanged(object sender, TextChangedEventArgs e)
        {
            e.Handled = true;
            RoutedEventArgs args = new RoutedEventArgs(FileNameChangedEvent);
            RaiseEvent(args);
        }


        public string FileName
        {
            get { return (string)GetValue(FileNameProperty); }
            set { SetValue(FileNameProperty, value); }
        }

        //注册用户控件事件
        public event RoutedEventHandler FileNameChanged
        {
            add { AddHandler(FileNameChangedEvent, value); }
            remove { RemoveHandler(FileNameChangedEvent, value); }
        }
        //注册依赖属性
        public static readonly DependencyProperty FileNameProperty =
           DependencyProperty.Register("FileName", typeof(string), typeof(FileInputBox));
        
        public static readonly RoutedEvent FileNameChangedEvent =
            EventManager.RegisterRoutedEvent("FileNameChanged",
            RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(FileInputBox));
    }

3.打开一个Windows窗体,可在工具箱看到用户控件FileInputBox,直接拖拽到Windows窗体上,就可以和微软的常规控件一样使用了。

XAML代码如下:

<Window x:Class="FileInputBox.Window2"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window2" Height="300" Width="300" xmlns:my="clr-namespace:Chapter16">
    <Grid>
        <my:FileInputBox HorizontalAlignment="Left" Margin="12,84,0,0" x:Name="fileInputBox1" FileName="xx" FileNameChanged="fileInputBox1_FileNameChanged" VerticalAlignment="Top" Width="254" />
    </Grid>
</Window>

FileName 是用户控件自定义属性,FileNameChanged 用户控件自定义事件

原文地址:https://www.cnblogs.com/_ymw/p/3335597.html