使用BooleanToVisibilityConverter的WPF MVVM隐藏按钮 [英] WPF MVVM hiding button using BooleanToVisibilityConverter
问题描述
在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屋!