将 MenuItem 属性 (IsEnabled) 绑定到同一控件中的组合框属性 (SelectedIndex)
我花了一天的大部分时间来研究这个问题;我很好奇是否可以在 XAML 中完全执行简单绑定,而不需要在后面的代码中实现 INotifyPropertyChanged。
讽刺的是,就我花在研究这个问题上的时间而言,我本可以在后台代码中完成 5 次以上。
我遇到过一些建议使用 DataTriggers 的文章(对于 MenuItems,DataTrigger 必须位于 Style Trigger 内)。我已经尝试过这个,但它不能正常工作。
我怀疑 DataTrigger 由于 MenuItem 范围问题而找不到组合框,我在另一个线程中读取了该问题。
有人有什么建议吗?
代码:(没有构建或运行时错误,但属性未更新)
<ContextMenu>
<MenuItem Header="Do Something Neat" x:Name="MyMenuItem" Click="MyMenuItem_Click">
<MenuItem.Style>
<Style TargetType="{x:Type MenuItem}">
<Style.Triggers>
<Setter Property="IsEnabled" Value="True" />
<DataTrigger Binding="{Binding ElementName=MyComboBox, Path=SelectedIndex}" Value="-1">
<Setter Property="IsEnabled" Value="False" />
</DataTrigger>
</Style.Triggers>
</Style>
</MenuItem.Style>
</MenuItem>
</ContextMenu>
I've spent a good portion of my day researching this; I'm curious if it's possible to do simple binding fully in XAML, without the need to implement INotifyPropertyChanged in the code behind.
Ironically, in the amount of time I've spent researching this I could have just done it in the code behind 5 times over.
I've come across a few articles that suggest using DataTriggers (for MenuItems, the DataTrigger must be inside the a Style Trigger). I've tried this, but it doesn't work without error.
I suspect the DataTrigger couldn't find the combobox because of MenuItem scope issues, which I read in a different thread.
Anyone have any suggestions?
Code: (no build or runtime errors, but property not updated)
<ContextMenu>
<MenuItem Header="Do Something Neat" x:Name="MyMenuItem" Click="MyMenuItem_Click">
<MenuItem.Style>
<Style TargetType="{x:Type MenuItem}">
<Style.Triggers>
<Setter Property="IsEnabled" Value="True" />
<DataTrigger Binding="{Binding ElementName=MyComboBox, Path=SelectedIndex}" Value="-1">
<Setter Property="IsEnabled" Value="False" />
</DataTrigger>
</Style.Triggers>
</Style>
</MenuItem.Style>
</MenuItem>
</ContextMenu>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我将默认设置器移至
Style.Triggers
之前(由于编译错误),将所有内容放入Menu
(以简化示例)并使其在索引上触发code>0
(更好地演示结果)。以下作品:I moved the default setter to before
Style.Triggers
(because of a compile error), put everything into aMenu
(to simplify the example) and made it trigger on index0
(to better demonstrate the result). The following works: