如何在ViewModel中将按钮的可见性绑定到bool值?
<Button Height="50" Width="50" Style="{StaticResource MyButtonStyle}" Command="{Binding SmallDisp}" CommandParameter="{Binding}" Cursor="Hand" Visibility="{Binding Path=AdvancedFormat}" />
假设AdvancedFormat为bool,则需要声明并使用BooleanToVisibilityConverter:
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}。
Converter={StaticResource BoolToVis}
在使用MVVM时,这是一种非常常见的模式。从理论上讲,您可以自己在ViewModel属性上进行转换(即,仅使属性本身成为type Visibility),但是我不愿意这样做,因为现在您 正在 关注关注点的分离。项的可见性实际上应该取决于View。
Visibility