【发布时间】:2013-03-28 17:21:00
【问题描述】:
您好,我在WPF application 中使用System.Windows.Forms.FolderBrowserDialog 来选择用户计算机中的文件夹。所选文件夹显示在 TextBox 中,并且也在视图模型中得到验证。
我正在尝试在TextBox 下方显示无效文件夹Error Template 消息以用于以下情况:
- 如果文件夹不存在且无法访问。
- 如果用户选择的文件夹是系统文件夹。对于此示例,我将值硬编码为
@"c:\windows\boot"。
我注意到的是:如果我键入一个不存在的文件夹,我会得到允许我设置错误模板的绑定异常。
但是,如果我选择了一个用户无权访问的驱动器,或者我选择了@"c:\windows\boot",我将得到一个异常,该异常要么在App.xaml unhandle 异常中捕获,要么如果你有一个try catch(文件夹所在的位置已设置)它将被捕获在那里。我怎样才能将其作为绑定异常?在我决定将它作为尝试捕获之前,我想了解是否有任何方法可以将其作为绑定异常(这样可以节省点击!)。
代码如下:
public class MainWindowViewModel : INotifyPropertyChanged
{
public MainWindowViewModel()
{
}
private string _folderName;
public string FolderName
{
get { return _folderName; }
set
{
_folderName = value;
if (!string.IsNullOrEmpty(_folderName))
InvalidValidFolder();
if (!string.IsNullOrEmpty(_folderName))
ValidateFolder();
OnPropertyChanged("FolderName");
}
}
private void ValidateFolder()
{
if (!Directory.Exists(FolderName))
throw new Exception("Folder does not exist");
}
private void InvalidValidFolder()
{
if (FolderName.ToLower() == @"c:\windows\boot")
throw new Exception("This folder is restricted.");
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
我只有MainWindow 和MainWindowViewModel。
<DockPanel>
<Grid DockPanel.Dock="Top" Width="Auto" Margin="50">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBox x:Name="textBox" Text="{Binding FolderName, ValidatesOnExceptions=True, ValidatesOnDataErrors=True}" Margin="0,0,0,5" Grid.Column="0" />
<Button Grid.Column="1"
Margin="5,0,5,0"
Width="35"
Content="..."
Click="LocationChoose_Click"/>
</Grid>
<Grid></Grid>
</DockPanel>
代码隐藏
public partial class MainWindow : Window
{
public MainWindowViewModel ViewModel {get; set;}
public MainWindow()
{
InitializeComponent();
this.DataContext = ViewModel = new MainWindowViewModel();
}
private void LocationChoose_Click(object sender, RoutedEventArgs e)
{
try
{
FolderBrowserDialog folderDlg = new FolderBrowserDialog();
folderDlg.ShowDialog();
ViewModel.FolderName = folderDlg.SelectedPath;
}
catch (Exception ex)
{
System.Windows.MessageBox.Show(ex.Message);
}
}
}
【问题讨论】:
标签: c# wpf folderbrowserdialog errortemplate