我需要创建一个自定义组合框控件,允许标题作为分隔符,不能使用鼠标移动或按键选择.
这是一个例子:
Header1 item1 item2 item3 Header2 item4 item5
我尝试了很多解决方案,没有成功.提前致谢!
解决方法
再次,WPF可以轻松提供解决方案,需要在winforms中进行大量可怕的黑客攻击.
将我的代码复制并粘贴到文件中 – >新项目 – > Visual Studio中的WPF应用程序.
您很快就会注意到我的解决方案不仅为Header Items提供了不同的视觉外观,而且还可以防止不必要的选择,无论是通过鼠标还是键盘,并且它不需要子类化常规的ComboBox类,这会导致较小的可维护性.
XAML:
<Window x:Class="WpfApplication5.Window2" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfApplication5" Title="Window2" Height="300" Width="300"> <Grid> <ComboBox ItemsSource="{Binding}" DisplayMemberPath="DisplayText" VerticalAlignment="Center" HorizontalAlignment="Center" Height="25" Width="100"> <ComboBox.ItemContainerStyle> <Style TargetType="ComboBoxItem"> <Setter Property="Foreground" Value="Black"/> <Style.Triggers> <DataTrigger Binding="{Binding IsHeader}" Value="True"> <Setter Property="IsEnabled" Value="False"/> <Setter Property="FontWeight" Value="Bold"/> </DataTrigger> <DataTrigger Binding="{Binding IsHeader}" Value="False"> <Setter Property="Margin" Value="10,0"/> </DataTrigger> </Style.Triggers> </Style> </ComboBox.ItemContainerStyle> </ComboBox> </Grid> </Window>
代码背后:
using System.Collections.Generic; using System.Windows; namespace WpfApplication5 { public partial class Window2 : Window { public Window2() { InitializeComponent(); var list = new List<ComboBoxItem> { new ComboBoxItem {DisplayText = "Header1",IsHeader = true},new ComboBoxItem {DisplayText = "Item1",IsHeader = false},new ComboBoxItem {DisplayText = "Item2",new ComboBoxItem {DisplayText = "Item3",new ComboBoxItem {DisplayText = "Header2",new ComboBoxItem {DisplayText = "Item4",new ComboBoxItem {DisplayText = "Item5",new ComboBoxItem {DisplayText = "Item6",}; DataContext = list; } } public class ComboBoxItem { public string DisplayText { get; set; } public bool IsHeader { get; set; } } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。