简体   繁体   中英

Why do combobox items take the whole screen if added dynamically but only the cbx's width when set in the XAML?

I just don't understand why, technically there's no extra style set anywhere else. If I add them in the XAML file, I do see the dropdown menu but otherwise, the comboxes I populate dynamically, fill up all the screen when expanded :(

I'm only setting the resources an array as my source

    comboPredict.ItemsSource = predValues;
    comboPredict.SelectedIndex = 0;

So after reading it right...

The WPF ComboBox will set automatically to the widest element in the drop down list. The ComboBox uses a Popup element to hold the list.

A Popup is sized to its content by default.

In the MSDN ComboBox.ItemSource description you can read:

When the ItemsSource property is set, the Items collection is made read-only and fixed-size.

So it will applying a RenderTransform on the Popup after setting the value.

It's also important to look at the parent of your control in the Visual-Tree of WPF.


Work-Around 1: Set the Width explicitly

Which causing problems if you change Font-Size or Format or you're not sure how long the text of Item will be.

Work-Around 2: Pavel's Solution

This is not the “WPF way”

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM