Posts

Showing posts with the label XAML

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; ...

Silverlight 2 crashing with SelectedItem/SelectedIndex after repopulating ComboBox

I have a Silverlight form with a ComboBox that is populated with all 50 States. Whenever a state is chosen, a list of cities are retrieved and sent back to another ComboBox. // Remove the old cities and populate with the new cities, selecting // the proper city if it exists for the user profile. Cities.Items.Clear(); ComboBox item = new ComboBoxItem(); item.Content = "Other"; Cities.Items.Add(item); Cities.SelectedItem = item; foreach(string city in retrievedCities) { item = new ComboBoxItem(); item.Content = city; Cities.Items.Add(item); if(city == db_profile_city) Cities.SelectedItem = item; } This block of code above crashes when the SelectedItem of Cities is changed, not with an exception but Application_Exit is called. When the items are cleared from the ComboBox, the selected indicies don't seem to be updated, so when the SelectedItem is changed, the engine crashes with the 'white screen of death'. The fix to this is to call Cities.UpdateLayout() afte...