【问题标题】:WPF - How Enable Button on Check the RadioButton using Validation RulesWPF - 如何启用按钮检查单选按钮使用验证规则
【发布时间】:2017-01-18 05:33:17
【问题描述】:

我刚开始学习 WPF,如有任何愚蠢的问题,请提前道歉。如果所有输入都没有验证错误,我想启用一个按钮。这是我的示例输入窗口:

<StackPanel>

    ...rest of my page

    <Label>Age:</Label>
    <TextBox>
        <TextBox.Text>
            <Binding Path="Age" UpdateSourceTrigger="PropertyChanged"/>
                <Binding.ValidationRules>
                    <ExceptionValidationRule />
                </Binding.ValidationRules
            </Binding>
        </TextBox.Text>
    </TextBox>
    <Label>Options:</Label>
    <RadioButton>Option one</RadioButton>
    <RadioButton>Option two</RadioButton>
    <Button Name="btnOK" MinWidth="40" Command="c:CustomCommands.Enter">Ok</Button>
</StackPanel>

在我的后台代码中,按钮的 CanExecute 方法为:

private void EnterCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
    e.CanExecute = isValid(sender as DependencyObject);
}

private bool IsValid(DependencyObject obj)
{
    return !Validation.GetHasError(obj) && LogicalTreeHelper.GetChildren(obj).OfType<DependencyObject>().All(IsValid);
}

我在谷歌上看到人们只向一个 RadioButton 添加验证规则,例如在Validation Rule for Radio buttons wpf 中。

我需要的是,当取消选择所有 RadioButton 时,它应该添加一个验证错误,这样按钮就会被 IsValid 方法禁用。如果选择了任何 RadioButton,如果 Age 也为“ok”,则该按钮将被启用。

另外,我需要知道 RadioButton 部分在模型视图类中的情况。

谢谢!

【问题讨论】:

    标签: c# wpf validation button radio-button


    【解决方案1】:

    根据 Stígandr 在本主题中的回答 (Bind IsEnabled property to Boolean in WPF),您只需在 viewModel 中创建一个属性并将 Radiobutton IsEnabled / IsChecked 属性绑定到该属性即可。

    您可以在方法中设置该属性。

    private bool IsValid(DependencyObject obj)
    {
        return !Validation.GetHasError(obj) && LogicalTreeHelper.GetChildren(obj).OfType<DependencyObject>().All(IsValid);
        yourProperty = value;
    }
    

    然后它会更新你的 UI。

    在你的情况下,

    在 viewModel 中创建一个绑定到 yourProperty 的依赖属性。

    private static readonly DependencyProperty IsFormValidProperty =
        DependencyProperty.Register(
            "IsFormValid",
            typeof(bool),
            typeof(YourControl),
            new FrameworkPropertyMetadata(false, new PropertyChangedCallback(OnValidationChanged))
            );
    
    privatestaticvoid OnValidationChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
        // here , if e.newValue is true then
        //you can set button's IsEnabled property to true.
    }
    

    【讨论】:

    • 嗨@FreeMan,感谢您的帮助。我不确定这个解决方案是否能解决我的问题。仅当单选按钮之外的任何输入中没有验证错误时,才应启用该按钮。它由 CanExecute 命令方法控制。您建议创建另一种方法来控制可见性,然后有时会由 IsValid 启用,有时会由 OnValidationChanged 启用?另外,我相信您的意思是在返回之前使用 yourProperty = value; ,对吗?
    猜你喜欢
    • 2014-12-23
    • 2012-12-28
    • 1970-01-01
    • 2011-04-16
    • 1970-01-01
    • 2011-10-20
    • 1970-01-01
    • 1970-01-01
    • 2013-10-28
    相关资源
    最近更新 更多