Posts

Showing posts with the label WPF

WPF ComboBox Adjusting to Parent Grid size or Max Width of Item

I was messing around with WPF the other day and had a ComboBox as part of a grid. Instead of the ComboBox either being the max width of the cell or a set width, I wanted the ComboBox to be the max width of a child item with a maximum of the cell size (I don't want the ComboBox to overflow the cell). I came up with the code below, and can be adapted to other panel types but is focused on the ComboBox being in a cell of the Grid. public class ComboBoxEx : ComboBox { public override void OnApplyTemplate() { base.OnApplyTemplate(); Loaded += AdjustWidth; FrameworkElement element = Parent as FrameworkElement; if (element != null) element.SizeChanged += AdjustWidth; } protected override void OnVisualParentChanged(DependencyObject oldParent) { base.OnVisualParentChanged(oldParent); FrameworkElement element = oldParent as FrameworkElement; if (element != null) element.SizeChanged -= AdjustWidth; ...