Button.CommandProperty绑定到ViewModel的SomeObject.SomeCommand属性。当SomeObject的SomeCommand属性设置为null或整个SomeObject属性设置为null时,此按钮保持启用状态。在这种情况下如何禁用按钮?
我正在使用MVVM创建应用程序,其行为类似于浏览器: 主view_model(对应于主窗口作为视图)具有Workspace view_models列表。每个工作区view_model对应于Windows的TabControl中的TabPage。 主view_model具有CurrentWorkspace属性,该属性对应当前活动的TabPage。
在主窗口中,这是一个带按钮的工具栏,它使用CurrentWorkspace提供的命令。例如,对重新加载工作空间数据的访问实现为:
<Button Name="btReload" Content="Reload"
Command="{Binding Path=CurrentWorkspace.ReloadCommand, UpdateSourceTrigger=PropertyChanged}"/>
我尝试通过创建DataTriggers来完成按钮禁用的任务,但似乎触发器只能在第一次工作而不再工作:
<Button Name="btReload" Content="Reload"
Command="{Binding Path=CurrentWorkspace.ReloadCommand, UpdateSourceTrigger=PropertyChanged}">
<Button.Style>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding Path=CurrentWorkspace, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" Value="{x:Null}">
<Setter Property="dxb:BarButtonItem.IsEnabled" Value="False"/>
</DataTrigger>
<DataTrigger Binding="{Binding Path=CurrentPage.CurrentWorkspace, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" Value="{x:Null}">
<Setter Property="dxb:BarButtonItem.IsEnabled" Value="False"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
它看起来真的很愚蠢:就像MS Word一样,无文档客户区,同时工具栏中有很多现成的点击按钮(带格式化和其他特定于文档的功能)。请帮助我:),
P.S。向工具栏添加一个DataContext绑定到CurrentWorkspace的按钮时,在窗口中激活或添加或删除工作区选项卡时,其DataContextChanged事件会正常触发。所以,DataTrigger中的问题(或者通常是View中的问题),而不是它的ViewModel(s)。
我在VS2010上传了示例项目,链接存档:http://www.filefactory.com/file/b43455e/n/WhatIfCommandIsNull.rar
低于其描述。
正如您所看到的,当Window.DataContext设置为ViewModel实例时,两个命令都正常工作,&amp; ResetDataCommand.CanExecute也正常工作(当ViewModel.Data为NULL时,ResetDataCommand.CanExecute返回false&amp; button btResetData被禁用)。一旦Window.DataContext设置为null,最后两个按钮启用(对于前两个按钮,没有命令被绑定)。
问题是要以声明方式(通过触发器)实现接下来的四条规则:
我认为使用触发器可以实现前两个规则,其次是使用DataTriggers。但他们没有工作,所以我从项目中删除了它们。
答案 0 :(得分:7)
这可能有效(等待你的情况)
<Button.Style>
<Style TargetType="{x:Type Button}">
<Style.Triggers>
<Trigger Property="Command" Value="{x:Null}">
<Setter Property="IsEnabled" Value="false"/>
</Trigger>
</Style.Triggers>
</Style>
</Button.Style>