通过数据绑定禁用按钮
我有一个树视图和一个删除按钮,我希望仅在选择树视图项目时才启用删除按钮。
我已尝试以下操作,但它不起作用:
<Button.Style>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=tv_cats, Path=Items.IndexOf(SelectedItem)}" Value="-1">
<Setter Property="Button.IsEnabled" Value="false" />
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
测试 - 在后面的代码中 -
tv_cats.Items.IndexOf(tv_cats.SelectedItem).ToString()
如果未选择电视项目,则返回 -1;如果选择了电视项目索引,则返回 -1。
如何在 XAML 中使用此属性?
I have a treeview and a delete button, I want the delete button to be enabled only if a treeview item is selected.
I have tried the following but it doesn't work:
<Button.Style>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=tv_cats, Path=Items.IndexOf(SelectedItem)}" Value="-1">
<Setter Property="Button.IsEnabled" Value="false" />
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
to test - in code behind -
tv_cats.Items.IndexOf(tv_cats.SelectedItem).ToString()
Returns -1 if tv item not selected and tv items index if it is.
How can I use this property in XAML?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有几种方法可以做到这一点,
通过按钮上的触发器来评估 TreeView 的 selectedItem 属性(按钮默认情况下处于启用状态,当 SelectedItem="{x:Null}" 时启用为 false
通过将项目存在性转换为布尔值的转换器 (Implements IValueConverter)。
Couple of ways to do this,
Through triggers on the button that evaluate the selectedItem property of the TreeView (Button is enabled by default, Enabled is false when SelectedItem="{x:Null}"
An element property binding from button.Enabled to TreeView.SelectedItem through a converter (Implements IValueConverter) that converts the item existence to a boolean value.
In MVVM, you can have a ButtonIsEnabled property exposed on your ViewModel which checks the value of the SelectedItem in some fashion (Easiest is to have the TreeViews Selected Item property bound to another property on the VIewModel as well) and determing enabled status from that.
请尝试以下操作:
确保按钮 XAML 声明中没有显式声明 IsEnabled="false"。否则触发器将无法工作。
Try the following:
Make sure that you don't have an explicit declaration of IsEnabled="false" in the Buttons XAML declaration. Otherwise the trigger will not work.