WPF/MVVM: Disable a Button's state when the Vi

2019-02-06 18:25发布

I have a DocumentListView.Xaml with a ListBox and 3 Buttons.

Behind that UserControl sits a DocumentListViewModel with 3 Buttons and their Command Property bound to 3 RelayCommands.

I have 3 Controller like AdministrationController, BillingController, ReportController.

Every Controller has ObservableCollections like Customer 1 : N Order 1: N Document same for the other Controller.

In one Controller I have a special binding situation. When my DocumentListViewModel is not initialized by its parent ViewModel like OrderViewModel (because no orders are loaded/exist) then my UserControl has 3 buttons which are ENABLED. Ok the user can press the 3 buttons and nothing happens but still its very confusing and above all the consistency in my user interface is gone.

How can I set the Command of a Button as default to "Disabled" ?

Setting the Buttons IsEnabled property to false does not help because the button will stay forever in the disabled state. No CanExecute TRUE will set it to IsEnabled = true.

AND I do not want to introduce another property IsButtonEnabled... that stupid because then I have both worlds winforms and wpf behind my buttons logic... ICommand should be enough.

2条回答
淡お忘
2楼-- · 2019-02-06 18:43

Or you can use a Style for the button to disable:

<Style TargetType="{x:Type Button}" x:Key="DisablerButton">
    <Style.Triggers>
        <Trigger Property="Command" Value="{x:Null}">
            <Setter Property="IsEnabled" Value="False" />
        </Trigger>
    </Style.Triggers>
</Style>
查看更多
Deceive 欺骗
3楼-- · 2019-02-06 18:55

This is an interesting situation. Honestly I've never run into the case where the UI was loaded and interactive but the ViewModel was not yet bound.

However, ignoring that for a moment, you could potentially use a FallbackValue on your binding to bind to a globally available NullCommand or something that always returns false for its CanExecute method.

<Button Command="{Binding SaveCommand, FallbackValue={StaticResource NullCommand}}" />
查看更多
登录 后发表回答