使用 BooleanToVisibilityConverter 的 WPF MVVM 隐藏按钮 [英] WPF MVVM hiding button using BooleanToVisibilityConverter

查看:31
本文介绍了使用 BooleanToVisibilityConverter 的 WPF MVVM 隐藏按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 WPF 应用程序中,我试图根据用户选择的选项更改按钮的可见性.在加载时,我希望其中一个按钮不可见.我正在使用内置值转换器 BooleanToVisibilityConverter.但是它不起作用,因为按钮在加载时出现.我已将属性更改为 true 和 false,没有区别.下面是我的代码,我看不到我遗漏了什么?

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 using the in built value converter BooleanToVisibilityConverter. However it's not working as the button is appearing at load time. I have changed the property to both true and false, makes no difference. Below is my code, I can't see what I'm missing?

我的视图模型中的属性

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

在我的 app.xaml 中

In my app.xaml

 <Application.Resources>       
    <BooleanToVisibilityConverter x:Key="BoolToVis"/>

在我的 MainWindow.xaml 中

In my MainWindow.xaml

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

推荐答案

对于初学者来说,如果你使用的是 Command,那么你不需要绑定 IsEnabled,这应该由命令实现来决定.

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

其次,ViewModel 与 View 的绑定往往发生在稍晚的阶段,所以最好也为绑定设置一个默认值,就像这样

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

第三,正如 Mike 所指出的,确保您的属性是公开的,因为 ViewModel 和 View 是两个独立的类.

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

这篇关于使用 BooleanToVisibilityConverter 的 WPF MVVM 隐藏按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆