c# - 将 Button 的可见性绑定(bind)到 ViewModel 中的 bool 值

标签 c# wpf xaml data-binding

如何将按钮的可见性绑定(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/

相关文章:

c# - 一旦结果不能再改变,C# LINQ 聚合方法是否完成执行?

c# - 构建不同类型的相关项目的集合

c# - FindVisualChild引用问题

c# - 验证错误阻止调用属性 setter

c# - 使用获取 "Object reference not set to an instance of an object"的任务

C#和MySql插入数据错误

c# - 'Event' 的无效值 - 属性 (XAML Eventsetter)

c# - 防止键盘打开时页面屏幕向上滚动(C#-XAML-Windows Store App)

wpf - 绑定(bind)转换器参数

c# - Visual Studio 2010 —选择的解决方案配置会影响批量生成的输出