I have to disable a some button.
How I can use TextBox.Triggers for that?
Are there any samples?
Thank you for reply!
I am assuming this is related to your other question about triggering the Enabled property on a Button based on if a TextBox has a validation error or not.
If that's so, you would use a DataTrigger
to test the TextBox.Validation.HasError
property to see if it has any errors, and if so disable the Button
<Style x:Key="MyButtonStyle" TargetType="{x:Type Button}">
<Setter Property="IsEnabled" Value="True" />
<DataTrigger Binding="{Binding ElementName=MyTextBox, Path=Validation.HasError" Value="True">
<Setter Property="IsEnabled" Value="False"/>
</DataTrigger>
</Style>
Be sure you bind your TextBox with ValidatesOnDataErrors="True"
for this to work
<TextBox x:Name="MyTextBox" Text="{Binding SomeText, ValidatesOnDataErrors=True }" />
As a side note, my comment on your other question still applies here. I would personally implement IDataErrorInfo
in your ViewModel
and make the SaveCommand.CanExecute()
only return true if ViewModel.IsValid
. Then it will automatically take care of disabling the button if the SaveCommand
is not supposed to execute
Let's say you have a TextBox
and a Button
, and you want to disable your Button
when TextBox
is empty. This can be easily achieved with DataTriggers
:
<TextBox x:Name="textBox" />
<Button>
<Button.Style>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding Text, ElementName=textBox}" Value="">
<Setter Property="Button.IsEnabled" Value="False" />
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
Although posting code sample would be helpful and would allow a much better solution, I can still recommend data binding. Something like
<Button Name="btnFoo"
Enabled="{Binding ElementName=txtblkBar, Converter={StaticResource ButtonVisibilityConverter}"/>
where the resources section of your control contains
<local:ButtonVisibilityConverter Name="ButtonVisibilityConverter"/>
and you have defined a class ButtonVisibilityConverter
in the namespace referenced by local. The Data Conversion section of the page I linked to above has an example converter class.
EDIT:
Code that sets the button to disabled whenever txtblkBar
is empty:
[ValueConversion(typeof(TextBlock), typeof(bool?))]
public class ButtonVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
TextBlock txtblk = value as TextBlock;
if (null == txtblk)
return false;
return !string.IsNullOrEmpty(txtblk.Text);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
// Don't need to use the back conversion
throw new NotImplementedException();
}
}