In the Loaded
window handler, I create a ComboBox
and add it to the Grid
window. When you start the ComboBox
application, it draws incorrectly (Fig. 1) and is displayed so until I hover the mouse on it (Fig. 2).
Why is this happening and how can this be fixed by leaving the creation and addition of a ComboBox
in the Loaded
handler?
XAML:
<Window x:Class="WpfTest.MainWindow" xmlns="schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="schemas.microsoft.com/winfx/2006/xaml" SizeToContent="WidthAndHeight"> <Grid x:Name="mainGrid" /> </Window>
Code behind:
public MainWindow() { InitializeComponent(); Loaded += MainWindow_Loaded; } private void MainWindow_Loaded(object sender, RoutedEventArgs e) { var comboBox = new ComboBox { Width = 100, Margin = new Thickness(50) }; mainGrid.Children.Add(comboBox); comboBox.Items.Add(new TextBlock { Text = "Item 1" }); comboBox.Items.Add(new TextBlock { Text = "Item 2" }); comboBox.Items.Add(new TextBlock { Text = "Item 3" }); comboBox.SelectedIndex = 1; }
Upd: How to make the installation SelectedIndex
immediately select the specified item?
Children.Add
operation to move to the very end of the code, after selectingSelectedIndex
. - Monk