2016-09-10 79 views
1

我剛開始學習WPF,對於任何愚蠢的問題提前抱歉。如果所有輸入都沒有驗證錯誤,我想啓用一個按鈕。這是我的例子輸入窗口:WPF - 如何使用驗證規則檢查RadioButton啓用按鈕

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

我看到的谷歌人加入驗證規則只有一個單選按鈕,如Validation Rule for Radio buttons wpf

我需要的是當所有的RadioButton都未被選中時,它應該添加一個驗證錯誤,這樣Button就會被IsValid方法禁用。如果任何RadioButton被選中,按鈕將被啓用,如果年齡也是「好的」。

此外,我需要知道它是如何在模型視圖類的RadioButton部分。

謝謝!

回答

0

根據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; 
} 

然後它將更新您的用戶界面。

在你的情況,

創建結合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. 
} 
+0

嗨@FreeMan,謝謝你的幫助。我不確定這個解決方案是否能解決我的問題。只有在除了單選按鈕之外的任何輸入中沒有驗證錯誤的情況下,才能啓用該按鈕。它由CanExecute命令方法控制。您建議創建另一種方法來控制可見性,然後有時會由_IsValid_啓用,有時由_OnValidationChanged_?啓用。另外,我相信你的意思是使用_yourProperty = value; _在返回之前,對吧? – renatogbp