绑定按钮能见度在视图模型bool值 [英] Binding a Button Visibility to bool value in ViewModel
问题描述
我想一个按钮的可见性绑定到我的视图模型一个布尔值。
我怎样才能做到这一点?我看见有几个类似的问题在这里#2,但没有得到正是我想要的。
我有这个,但我怎么能绑定到我的虚拟机一个bool。
<按钮
HEIGHT =50WIDTH =50
风格={StaticResource的MyButtonStyle}
命令={结合SmallDisp}CommandParameter ={结合}
光标=手能见度={绑定路径= AdvancedFormat}/>
假设 AdvancedFormat
是布尔
,你需要声明并使用<一个href=\"http://msdn.microsoft.com/en-us/library/system.windows.controls.booleantovisibilityconverter%28v=vs.110%29.aspx\"><$c$c>BooleanToVisibilityConverter$c$c>:
&LT;! - 在XAML你的资源部分 - &GT;
&LT; BooleanToVisibilityConverter X:键=BoolToVis/&GT;&LT;! - 在你的按钮声明 - &GT;
&LT;按钮
HEIGHT =50WIDTH =50
风格={StaticResource的MyButtonStyle}
命令={结合SmallDisp}CommandParameter ={结合}
光标=手能见度={绑定路径= AdvancedFormat,转换器= {StaticResource的BoolToVis}}/&GT;
请注意添加 =转换器的StaticResource {} BoolToVis
。
这与MVVM工作时是一个很常见的模式。从理论上讲,你可以做的视图模型属性自己的转换(即只是做类型的物业本身能见度
),虽然我会preFER不这样做,因为现在您的是的与关注点分离搞乱。一个项目的visbility确实应该到视图。
I want to bind the visibility of a button to a bool value in my ViewModel. How can I accomplish this? I saw a couple of similar questions here on Stackoverflow but didn't get exactly what I wanted.
I have this but how can I bind it to a bool in my VM.
<Button
Height="50" Width="50"
Style="{StaticResource MyButtonStyle}"
Command="{Binding SmallDisp}" CommandParameter="{Binding}"
Cursor="Hand" Visibility="{Binding Path=AdvancedFormat}"/>
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}}"/>
Note the added Converter={StaticResource BoolToVis}
.
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.
这篇关于绑定按钮能见度在视图模型bool值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!