WPF MVVM hiding button using BooleanToVisibilityConverter

后端 未结 2 909
天涯浪人
天涯浪人 2020-12-15 17:50

In my WPF application I am trying to change the visibility of a button depending on the options chosen by a user. On load I want one of the buttons to not be visible. I am u

相关标签:
2条回答
  • 2020-12-15 18:16

    For starters mate, if you're using a Command, then you don't need to bind IsEnabled, the command implementation should decide this.

    Secondly, the binding of a ViewModel to a View tends to happen at a bit of a later stage, so it's best to also set a default value for the binding, like so

    Visibility="{Binding ButtCancel, Converter={StaticResource BoolToVis}, FallbackValue=Hidden}"
    

    Third, as Mike pointed out, ensure that your property is public, since the ViewModel and the View are two separate classes.

    0 讨论(0)
  • 2020-12-15 18:16

    Instead of using a converter, you can just use a DataTrigger.

    <Button Grid.Column="2" Command="{Binding CommandButtProgressCancel}" Content="Cancel" 
            Visibility="{Binding ButtCancel, Converter={StaticResource BoolToVis}}" 
            IsEnabled="{Binding ButtCancelEnabled}" Height="50" Width="120"
            HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,0,50,20">
        <Button.Style>
            <Style TargetType={X:Type Button}>
                <!-- This would be the default visibility -->
                <Setter Property="Visibility" Value="Visible" />
                <Style.Triggers>
                    <DataTrigger Binding="{Binding ButtCancel, UpdateSourceTrigger=PropertyChanged}" Value="True">
                        <Setter Property="Visibility" Value="Hidden" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Button.Style>
    </Button>
    

    Update your ViewModel's properties to public

    public bool ButtCancel
    {
        get { return _buttCancel; }
        set
        {
            _buttCancel = value;
            OnPropertyChanged("ButtCancel");
        }
    }
    

    And make sure the DataContext of your MainWindow is set to the ViewModel.

    0 讨论(0)
提交回复
热议问题