您的位置:首页 > 其它

wpf选取文件夹的控件

2011-12-22 15:22 302 查看
在 《wpf揭秘》这本书里有类似的控件。
.cs文件
using System;

using System.Windows;

using System.Windows.Controls;

using Microsoft.Win32;

namespace Chapter16

{

[System.Windows.Markup.ContentProperty("FileName")]

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;

}

public string FileName

{

get { return (string)GetValue(FileNameProperty); }

set { SetValue(FileNameProperty, value); }

}

private void OnTextChanged(object sender, TextChangedEventArgs e)

{

e.Handled = true;

RoutedEventArgs args = new RoutedEventArgs(FileNameChangedEvent);

RaiseEvent(args);

}

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));

}

}

.xaml文件
<UserControl x:Class="Chapter16.FileInputBox"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

x:Name="root">

<DockPanel>

<Button x:Name="theButton" DockPanel.Dock="Right" Click="theButton_Click">Browse...</Button>

<TextBox x:Name="theTextBox" MinWidth="{Binding ActualWidth, ElementName=theButton}" Text="{Binding FileName, ElementName=root}" Margin="0,0,2,0"/>

</DockPanel>

</UserControl>

这个控件可以直接拿来用。它是选择文件的,我们需要修改函数
private void theButton_Click(object sender, RoutedEventArgs e)

{

FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();

if (folderBrowserDialog.ShowDialog() == DialogResult.OK)

{

this.FileName = folderBrowserDialog.SelectedPath;

}

}

FolderBrowserDialog 是using System.Windows.Forms;的一个控件。

关于这dialog在/article/6028094.html有详细说明。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: