AMissico
AMissico

Reputation: 21684

In WPF, How do I check a CheckBox based on a TextBox.Text value?

How do I check a CheckBox based on a TextBox.Text value?

I am have a little experience with WPF. I have an idea what can be done, but not much experience on how to get it done.

How do I check the __postCloseAudit check box through XAML based on the Text value of __postCloseAuditBy? If the Text length is greater than Zero, the check box should be checked.

<CheckBox x:Name="__postCloseAudit"
          Tag="{Binding LoginId}"
          Click="__postCloseAudit_Click">

    <WrapPanel>

        <TextBox x:Name="__postCloseAuditBy"
                 Width="94"
                 Text="{Binding PostCloseAuditBy }" />

        <TextBox x:Name="__postCloseAuditOn"
                 Width="132"
                 Text="{Binding PostCloseAuditOn }" />

    </WrapPanel>

</CheckBox>

Upvotes: 0

Views: 1611

Answers (1)

Jon
Jon

Reputation: 437356

You write a value converter and bind the IsChecked property to the text of the TextBox. The converter's job will be to take the text as an input and decide about the checked status based on its length; this will be in a separate class, so it's not exactly code-behind but it's close.

Example converter:

[ValueConversion(typeof(string), typeof(bool?))]
public class TextToIsBoolConverter : IValueConverter
{
    public object Convert(object value, Type targetType,
                          object parameter, CultureInfo culture)
    {
        var s = (string)value;
        return s.Length > 0;
    }

    public object ConvertBack(object value, Type targetType,
                              object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

And the binding would look like:

<CheckBox x:Name="__postCloseAudit"
  Tag="{Binding LoginId}"
  Click="__postCloseAudit_Click"
  IsChecked="{Binding ElementName=__postCloseAuditBy, Path=Text, Converter={StaticResource myConverter}}">

If you are using MVVM then your viewmodel should subsume the functionality of the converter and expose a calculated property based on the value of PostCloseAuditBy.

Upvotes: 1

Related Questions