WPF/MVVM: Disable a Button's state when the ViewModel behind the UserControl is not yet Initialized?

元气小坏坏 提交于 2019-11-29 13:43:49

问题


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.


回答1:


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>



回答2:


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}}" />


来源:https://stackoverflow.com/questions/4423746/wpf-mvvm-disable-a-buttons-state-when-the-viewmodel-behind-the-usercontrol-is

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!