如何将按钮的可见性绑定(bind)到我的 ViewModel 中的 bool 值?
<Button Height="50" Width="50" Style="{StaticResource MyButtonStyle}"
Command="{Binding SmallDisp}" CommandParameter="{Binding}" Cursor="Hand"
Visibility="{Binding Path=AdvancedFormat}" />
最佳答案
假设 AdvancedFormat
是一个 bool
,您需要声明并使用 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
类型),但我不希望这样做,因为现在您是搞乱关注点分离。项目的可见性实际上应该取决于 View 。
关于c# - 将 Button 的可见性绑定(bind)到 ViewModel 中的 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7000819/