Reputation: 474
Validation part `
Imports System.Globalization
Namespace Validation
Public Class ISBNLength
Inherits ValidationRule
Public Overrides Function Validate(value As Object, cultureInfo As CultureInfo) As ValidationResult
If value.ToString.Trim.Length = 10
Return New ValidationResult(True,"")
Else
Return New ValidationResult(False,"Must be a 10 digit number")
End If
End Function
End Class
End Namespace
**XAML**
<materialDesign:PackIcon Kind="BarcodeScan"
Grid.Row="1" Margin="0,0,16,10" />
<TextBox x:Name="TxtISBN"
Grid.Row="1"
materialDesign:HintAssist.Hint="ISBN Number" MaxLength="10" >
<TextBox.Text>
<Binding ElementName="TxtISBN" Path="Text" UpdateSourceTrigger="LostFocus">
<Binding.ValidationRules>
<validation:NotEmpty/>
<validation:ISBNLength/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
<Button
x:Name="BtnAccept"
IsDefault="True"
Command="materialDesign:DialogHost.CloseDialogCommand"
Content="ADD"
IsEnabled="False"
Height="36" Width="90" />
now I want to disable the button if the function returns false.
NOTE: I am not able to acess the dialog without creating a new instance of it.
Upvotes: 1
Views: 1269
Reputation: 169200
You could use a Style
with a DataTrigger
that binds to the Validation.HasError
attached property of the TextBox
:
<Button
x:Name="BtnAccept"
IsDefault="True"
Command="materialDesign:DialogHost.CloseDialogCommand"
Content="ADD"
Height="36" Width="90">
<Button.Style>
<Style TargetType="Button" BasedOn="{StaticResource {x:Type Button}}">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=(Validation.HasError), ElementName=TxtISBN}" Value="True">
<Setter Property="IsEnabled" Value="False" />
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
Also note that the TextBox
should bind to a source property. It cannot bind to its own Text
property.
Upvotes: 3
Reputation: 51653
Bind the Button`s Enabled to the input text and use a value converter: (no VB,sorry)
public static class Extensions
{
public static bool IsIsbn(this string s)
{
if ((s?.Trim() ?? "") is string isbn)
return s.Length == 10 /* && whatever */ ;
return false;
}
}
public class ValidIsbnToBoolConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is string s)
return s.IsIsbn();
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
=> throw new NotImplementedException();
}
public class ValidationRuleIsbn : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
return ((value as string)?.IsIsbn() ?? false)
? ValidationResult.ValidResult
: new ValidationResult(false, "Must be a 10 digit number");
}
}
Upvotes: 0