0

如何根据 TextBox.Text 值检查 CheckBox?

我对 WPF 有一点经验。我有一个想法可以做什么,但没有太多关于如何完成它的经验。

如何__postCloseAudit根据 Text 值通过 XAML 检查复选框__postCloseAuditBy?如果文本长度大于零,则应选中该复选框。

<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>
4

1 回答 1

1

您编写一个值转换器并将IsChecked属性绑定到TextBox. 转换器的工作是将文本作为输入,并根据其长度决定检查状态;这将在一个单独的类中,所以它不完全是代码隐藏,但它很接近。

示例转换器:

[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();
    }
}

绑定看起来像:

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

如果您使用的是 MVVM,那么您的视图模型应该包含转换器的功能并根据PostCloseAuditBy.

于 2013-04-29T22:57:23.687 回答