将Button的可见性绑定到ViewModel中的bool值 [英] Binding a Button's visibility to a bool value in ViewModel

查看:166
本文介绍了将Button的可见性绑定到ViewModel中的bool值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在一个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屋!

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