簡體   English   中英

WPF - 如何啟用按鈕使用驗證規則檢查RadioButton

[英]WPF - How Enable Button on Check the RadioButton using Validation Rules

我剛開始學習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);
}

我在google上看到人們只將驗證規則添加到一個RadioButton,就像在單選按鈕驗證規則wpf中一樣

我需要的是當所有RadioButton都被取消選中時,它應該添加一個驗證錯誤,這樣就可以通過IsValid方法禁用Button。 如果選擇任何RadioButton,如果Age也是“ok”,則啟用Button。

另外,我需要知道它在RadioButton部分的模型視圖類中是怎樣的。

謝謝!

根據Stígandr在本主題中的答案( 在WPF中將IsEnabled屬性綁定為布爾值 ),您只需在viewModel中創建一個屬性,並將Radiobutton IsEnabled / IsChecked屬性綁定到此屬性。

您可以在方法中設置該屬性。

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

然后它會更新你的用戶界面。

在你的情況下,

創建一個依賴項屬性,該屬性綁定到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.
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM