9

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.

THelper
  • 15,333
  • 6
  • 64
  • 104
Elisabeth
  • 20,496
  • 52
  • 200
  • 321

2 Answers2

23

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>
marcjohne
  • 171
  • 2
  • 11
Goblin
  • 7,970
  • 3
  • 36
  • 40
5

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}}" />
Josh
  • 68,005
  • 14
  • 144
  • 156
  • The problem is my DocumentListView is a UserControl used 3 times. When I do Command="{Binding SaveCommand, FallbackValue={x:Null}}" /> the SaveButton is still Enabled. But I would like to disable it via Commanding. – Elisabeth Dec 13 '10 at 18:56
  • Right, my example relies upon a globally available NullCommand, not the x:Null value which as you noted will enable the button. In any event, Goblin's workaround is probably easier to implement. – Josh Dec 14 '10 at 00:48
  • 1
    This is an extremely nice solution, especially for Silverlight. – Alastair Pitts Apr 24 '14 at 02:00