简体   繁体   English

C#WPF或ValidationRules之间的逻辑门

[英]C# WPF OR logical gate between ValidationRules

I'm using a combobox with validation and a save button as follows: 我正在使用带有验证和保存按钮的组合框,如下所示:

<ComboBox   ItemsSource="{Binding ...}" 
            x:Name="cmbGenerationTariff" IsEnabled="False" >
    <ComboBox.SelectedItem>
        <Binding Path="..." UpdateSourceTrigger="PropertyChanged" Mode="TwoWay">
            <Binding.ValidationRules>
                <common:ValidationRuleStringAnyLength  ValidatesOnTargetUpdated="True"/>
            </Binding.ValidationRules>
        </Binding>
    </ComboBox.SelectedItem>
</ComboBox>

...

<Button x:Name="btnSaveSite" Click="btnSave_Click"  Content="SAVE">
    <Button.Style>
        <Style TargetType="{x:Type Button}">
            <Setter Property="IsEnabled" Value="false" />
            <Style.Triggers>
                <MultiDataTrigger>
                    <MultiDataTrigger.Conditions>                           
                        <Condition Binding="{Binding ElementName=cmbGenerationTariff, Path=(Validation.HasError)}" Value="false" />
                        <Condition Binding="{Binding ElementName=cmbTimeZone, Path=(Validation.HasError)}" Value="false" />                         
                        <Condition Binding="{Binding ElementName=txtCity, Path=(Validation.HasError)}" Value="false" />
                        <Condition Binding="{Binding ElementName=cmbCountry, Path=(Validation.HasError)}" Value="false" />
                    </MultiDataTrigger.Conditions>
                    <Setter Property="IsEnabled" Value="true" />
                </MultiDataTrigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>

And it works just fine. 而且效果很好。 The save button is enabled iff all elements are valid. 如果所有元素均有效,则启用保存按钮。

What I want is for the save button to be enabled also when elements are disabled (in other words, I don't need to validate the values of disabled elements). 我想要的是在禁用元素时也启用保存按钮(换句话说,我不需要验证禁用元素的值)。

How can I do it? 我该怎么做? can I maybe use an 'OR' condition ( element is valid OR element is disabled )? 我可以使用“ OR”条件( 元素有效还是OR元素禁用 )?

As @Adi Lester put it, you'd probably be better off using MVVM pattern here. 正如@Adi Lester所说的,您最好在这里使用MVVM模式
Consider adding eg MVVMLight as dependency, via NuGet, to get started easier. 考虑通过NuGet添加例如MVVMLight作为依赖项,以更轻松地开始使用。

If you do, you'll have that much better control over your logic. 如果这样做,您将可以更好地控制逻辑。 Consider simple Window XAML 考虑简单的Window XAML

<Window.DataContext>
    <local:MainViewModel />
</Window.DataContext>
<StackPanel>
    <!--Bind to Text and IsEnabled properties in ViewModel-->
    <TextBox Text="{Binding Text, UpdateSourceTrigger=PropertyChanged}" 
             IsEnabled="{Binding IsEnabled}">
    </TextBox>
    <!--Bind to IsEnabled property in ViewModel-->
    <CheckBox Content="Text input enabled" 
              IsChecked="{Binding IsEnabled}">
    </CheckBox>
    <!--Bind to SaveCommand in ViewModel-->
    <Button Content="Save" 
            Command="{Binding SaveCommand}">
    </Button>
</StackPanel>

Where MainWindow codebehind is left as-is and MainViewModel (the DataContext) is MainWindow后面的代码保持原样, MainViewModel (DataContext)在此处

public class MainViewModel : ViewModelBase // <- MVVMLight ViewModel base class
{
    private string _text = null;
    private bool _isEnabled = true;

    public MainViewModel()
    {
        SaveCommand = new RelayCommand(
            // Execute command
            () => Console.WriteLine(@"Save command received, input value:{0}", Text),
            // Can execute command?
            () => !IsEnabled || (IsEnabled && !string.IsNullOrWhiteSpace(Text)));
    }

    public ICommand SaveCommand { get; set; }

    public string Text
    {
        get { return _text; }
        set { _text = value; RaisePropertyChanged(); }
    }

    public bool IsEnabled
    {
        get { return _isEnabled; }
        set { _isEnabled = value; RaisePropertyChanged(); }
    }
}

Tadah! Tadah! Now you have logic that toggles your Save button on when either text is entered or checkbox is left unchecked. 现在,你有你的切换逻辑Save按钮on时,输入文本或复选框听之任之。 And as additional bonus you are now officially Doing It Right ;) 作为额外的奖励,您现在可以正确地做到这一点;)

在此处输入图片说明

It doesn't look like you're using MVVM, but the correct thing to do would be to use a command for your button and have the CanExecute logic in your viewmodel. 看起来您不是在使用MVVM,但是正确的做法是对按钮使用命令,并在视图模型中包含CanExecute逻辑。 There you should be able to access the state of your data and perform more complex validation logic. 在那里,您应该能够访问数据状态并执行更复杂的验证逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM