WPF Validation not fired
I have a simple textbox and a button on a WPF form. When I click the button an OpenFolderDialog opens and I choose a folder. That SelectedPath is then shown in the textbox. This all works fine.
Then I 开发者_如何学编程decided I wanted validation on the textbox to check if the directory exists, because you can just paste some path in the textbox too. When my program starts the textbox shows a red border around it because the validation sees an empty textbox. For now I can live with that.
There are two problems:
- When I select a valid folder through the dialog, the PropertyChnged is fired, but is null and thus the validation never runs and the red border is still shown.
- When I just paste a valid directory in it, nothing is fired at all and the red border is still shown.
What am I doing wrong?
Below my code. I'm new to WPF so I appreciate every help I can get.
<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>
And here is my c# code:
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.");
}
}
Your binding path is just wrong, you can not bind via this
(it will look for a property called this
). It works as expected if the binding is correct.
精彩评论