将 Button 的可见性绑定到 ViewModel 中的 bool 值 [英] Binding a Button's visibility to a bool value in ViewModel
问题描述
如何将按钮的可见性绑定到 ViewModel 中的 bool 值?
How do I bind the visibility of a button to a bool value in my ViewModel?
<Button Height="50" Width="50" Style="{StaticResource MyButtonStyle}"
Command="{Binding SmallDisp}" CommandParameter="{Binding}" Cursor="Hand"
Visibility="{Binding Path=AdvancedFormat}" />
推荐答案
假设 AdvancedFormat
是一个 bool
,你需要声明并使用一个 BooleanToVisibilityConverter
:
Assuming AdvancedFormat
is a bool
, you need to declare and use a BooleanToVisibilityConverter
:
<!-- In your resources section of the XAML -->
<BooleanToVisibilityConverter x:Key="BoolToVis" />
<!-- In your Button declaration -->
<Button
Height="50" Width="50"
Style="{StaticResource MyButtonStyle}"
Command="{Binding SmallDisp}" CommandParameter="{Binding}"
Cursor="Hand" Visibility="{Binding Path=AdvancedFormat, Converter={StaticResource BoolToVis}}"/>
注意添加的Converter={StaticResource BoolToVis}
.
这是使用 MVVM 时非常常见的模式.从理论上讲,您可以自己在 ViewModel 属性上进行转换(即,只需将属性本身设为 Visibility
类型),尽管我不希望这样做,因为现在您是搞乱关注点的分离.项目的可见性应该真正取决于视图.
This is a very common pattern when working with MVVM. In theory you could do the conversion yourself on the ViewModel property (i.e. just make the property itself of type Visibility
) though I would prefer not to do that, since now you are messing with the separation of concerns. An item's visbility should really be up to the View.
这篇关于将 Button 的可见性绑定到 ViewModel 中的 bool 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!