【发布时间】:2011-10-06 16:22:09
【问题描述】:
我在 WPF 表单上有一个简单的文本框和一个按钮。当我单击按钮时,会打开 OpenFolderDialog 并选择一个文件夹。 SelectedPath 然后显示在文本框中。这一切都很好。
然后我决定要在文本框上进行验证以检查目录是否存在,因为您也可以在文本框中粘贴一些路径。 当我的程序启动时,文本框周围显示一个红色边框,因为验证看到一个空文本框。现在我可以忍受。
有两个问题:
- 当我通过对话框选择一个有效的文件夹时,PropertyChnged 被触发,但它为 null,因此验证永远不会运行,并且仍然显示红色边框。
- 当我只是在其中粘贴一个有效目录时,根本不会触发任何内容,并且仍然显示红色边框。
我做错了什么?
在我的代码下方。我是 WPF 的新手,所以我很感激我能得到的每一个帮助。
<TextBox Grid.ColumnSpan="2" Grid.Row="1" x:Name="textBoxFolder" Margin="2,4">
<TextBox.Text>
<Binding Path="this.MovieFolder" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<!-- Validation rule set to run when binding target is updated. -->
<Rules:MandatoryInputRule ValidatesOnTargetUpdated="True" />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
这是我的 c# 代码:
public partial class MainWindow : Window, INotifyPropertyChanged
{
private string _movieFolder;
public string MovieFolder
{
get { return _movieFolder; }
set
{
_movieFolder = value;
OnNotifyPropertyChanged("MovieFolder");
}
}
public MainWindow()
{
InitializeComponent();
//textBoxFolder.DataContext = MovieFolder;
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnNotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private void buttonSearchFolder_Click(object sender, RoutedEventArgs e)
{
FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
folderBrowserDialog.ShowDialog();
MovieFolder = folderBrowserDialog.SelectedPath;
textBoxFolder.Text = MovieFolder;
}
private void MenuItemClose_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
}
}
public class MandatoryInputRule : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
if (value != null)
{
string input = value as string;
if (Directory.Exists(input))
return new ValidationResult(true, null);
}
return new ValidationResult(false, "Not a valid folder.");
}
}
【问题讨论】:
-
抱歉代码乱码,我无法正确显示。
标签: c# wpf xaml data-binding validation