我在WPF表单上有一个简单的文本框和一个按钮。当我单击按钮打开OpenFolderDialog时,我选择了一个文件夹。然后,SelectedPath将显示在文本框中。一切正常。
然后我决定要在文本框上进行验证以检查目录是否存在,因为您也可以在文本框中粘贴一些路径。 当我的程序启动时,文本框会在其周围显示一个红色边框,因为验证会看到一个空文本框。现在我可以忍受。
有两个问题:
我做错了什么?
在我的代码下面。我是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.");
}
}
答案 0 :(得分:2)
您的绑定路径是错误的,您无法通过this
进行绑定(它将查找名为this
的属性)。如果绑定正确,它会按预期工作。