ToggleButton 组:确保始终在列表框中选择一项
我正在尝试复制 Word 中的左/中/右对齐工具栏按钮。单击“左对齐”按钮时,取消选中“居中”和“右对齐”按钮。我正在使用带有切换按钮的 WPF 列表框。
问题是用户可以单击“左对齐”按钮两次。第二次单击会取消选中该按钮并将基础值设置为 null。我希望第二次点击什么都不做。
有想法吗?强制列表框始终选择一项?防止视图模型中出现 null(需要刷新 ToggleButton 绑定)?
<ListBox ItemsSource="{x:Static domain:FieldAlignment.All}" SelectedValue="{Binding Focused.FieldAlignment}">
<ListBox.ItemTemplate>
<DataTemplate>
<ToggleButton IsChecked="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ListBoxItem}},Path=IsSelected}">
<TextBlock Text="{Binding Description}" />
</ToggleButton>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
I am trying to duplicate the left/center/right alignment toolbar buttons in Word. When you click the "Left Alignment" button the Center and Right buttons uncheck. I am using a WPF ListBox with ToggleButtons.
The problem is the user can click the Left Alignment button twice. The second click causes the button to uncheck and sets the underlying value to null. I'd like the second click to do nothing.
Ideas? Force the ListBox to always have one selected item? Prevent the null in the view model (need to refresh the ToggleButton binding)?
<ListBox ItemsSource="{x:Static domain:FieldAlignment.All}" SelectedValue="{Binding Focused.FieldAlignment}">
<ListBox.ItemTemplate>
<DataTemplate>
<ToggleButton IsChecked="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ListBoxItem}},Path=IsSelected}">
<TextBlock Text="{Binding Description}" />
</ToggleButton>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,对于这种情况,我也更喜欢单选按钮,但是如果您想使用切换按钮,那么也许您可以将 isenabled 属性绑定到 ischecked ,这样在检查时就无法单击它
yeah, i would prefer the radiobutton too for this case, but if you want to use togglebutton then maybe you can bind the isenabled property to ischecked so it cannot be cliked when it's checked
从 ToggleButton 创建自定义控件,
在 *.xaml.cs 文件中,在 *.xaml 中声明并定义控件
,将 ToggleButton 替换为 my:ToggleButton2,然后可以将 IsNotCheckable 绑定到 IsChecked,如下所示,
create custom control from ToggleButton,
in *.xaml.cs file, declare and define control
in *.xaml, replace ToggleButton with my:ToggleButton2, then you can bind IsNotCheckable to IsChecked, just like below,
我不会将其实现为 ToggleButtons,而是将 RadioButtons 与自定义模板一起使用。这可能会帮你省去很多麻烦。
Rather than implementing this as ToggleButtons, I would use RadioButtons with custom templates. It would probably save you a lot of headache.