123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- using System;
- using System.ComponentModel;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Forms;
- using System.Windows.Media;
- namespace CustomControls
- {
- [DesignTimeVisible(false)]
- public partial class OwnerDrawListBox : System.Windows.Controls.ListBox
- {
- private System.Drawing.Graphics measureGraphics;
- private System.Drawing.Graphics MeasureGraphics => measureGraphics ??= System.Drawing.Graphics.FromHwnd(IntPtr.Zero);
- public bool OwnerDraw
- {
- get { return (bool)GetValue(OwnerDrawProperty); }
- set { SetValue(OwnerDrawProperty, value); }
- }
- public readonly static DependencyProperty OwnerDrawProperty = DependencyProperty.Register(
- "OwnerDraw", typeof(bool), typeof(OwnerDrawListBox), new UIPropertyMetadata(false, (o, e) =>
- {
- if ((bool)e.NewValue == true)
- {
- var listBox = (OwnerDrawListBox)o;
- listBox.ItemContainerStyle = (Style)listBox.Resources["ItemContainerStyle1"];
- listBox.ItemHeight = 15;
- };
- }));
- public int ItemHeight
- {
- get { return (int)GetValue(ItemHeightProperty); }
- set { SetValue(ItemHeightProperty, value); }
- }
- public readonly static DependencyProperty ItemHeightProperty = DependencyProperty.Register(
- "ItemHeight", typeof(int), typeof(OwnerDrawListBox), new UIPropertyMetadata(19));
- public event DrawItemEventHandler DrawItem;
- public event MeasureItemEventHandler MeasureItem;
- internal void OnDrawItem(object sender, DrawItemEventArgs args) => DrawItem?.Invoke(this, args);
- internal Size OnMeasureItem(int index, Size size)
- {
- var args = new MeasureItemEventArgs(MeasureGraphics, index, ItemHeight);
- MeasureItem?.Invoke(this, args);
- size.Height = args.ItemHeight;
- return size;
- }
- public OwnerDrawListBox()
- {
- InitializeComponent();
- }
- }
- [DesignTimeVisible(false)]
- public class OwnerDrawListBoxItem : OwnerDrawItem
- {
- protected override void OnRender(DrawingContext drawingContext)
- {
- var listItem = WpfHelper.FindAncestor<System.Windows.Controls.ListBoxItem>(this);
- var listBox = ItemsControl.ItemsControlFromItemContainer(listItem) as OwnerDrawListBox;
- int index = listBox.ItemContainerGenerator.IndexFromContainer(listItem);
- OnDrawItem(drawingContext, index, listItem.IsSelected, listItem.IsEnabled, listItem.IsMouseOver, false, listBox.OnDrawItem);
- }
- protected override Size MeasureOverride(Size constraint)
- {
- var listItem = WpfHelper.FindAncestor<System.Windows.Controls.ListBoxItem>(this);
- var listBox = ItemsControl.ItemsControlFromItemContainer(listItem) as OwnerDrawListBox;
- int index = listBox.ItemContainerGenerator.IndexFromContainer(listItem);
- return listBox.OnMeasureItem(index, base.MeasureOverride(constraint));
- }
- }
- }
|