Why is this WPF ComboBox not showing the selected value?

天大地大妈咪最大 提交于 2019-12-04 18:30:53

QUICK ANSWER : Set SelectedIndex = 1 from code-behind.

It seems that the code in XAML executes first (the InitializeComponent() method), which sets SelectedIndex = 1, but ItemsSource is not specified yet! So SelectedIndex won't affect! (And remember, you cannot specify ItemsSource before InitializeComponent())

So you have to manually set SelectedIndex = 1 after setting ItemsSource.


You should do like this :

XAML

            <ComboBox x:Name="cbo"
                      Style="{StaticResource ComboStyle1}">
                <ComboBox.ItemTemplate>
                    <DataTemplate>
                        <Grid>
                            <TextBlock Text="{Binding Path=NAME}"/>
                        </Grid>
                    </DataTemplate>
                </ComboBox.ItemTemplate>
            </ComboBox>

Code

     cbo.ItemsSource = ser.GetCity().DefaultView;
     cbo.SelectedIndex = 1;

Or this:

XAML

            <ComboBox x:Name="cbo" Initialized="cbo_Initialized"
                      Style="{StaticResource ComboStyle1}">
                <ComboBox.ItemTemplate>
                    <DataTemplate>
                        <Grid>
                            <TextBlock Text="{Binding Path=NAME}"/>
                        </Grid>
                    </DataTemplate>
                </ComboBox.ItemTemplate>
            </ComboBox>

Code

    private void cbo_Initialized(object sender, EventArgs e)
    {
        cbo.SelectedIndex = 1;
    }

Also note that i've removed DisplayMemberPath="NAME" because you cannot set both DisplayMemberPath and ItemTemplate at the same time. And also, use either SelectedItem or SelectedIndex, not both.

Resetting the ItemsSource will mess up the selection.

Also, you are setting both SelectedItem and SelectedIndex. You want to set only one of these; if you set both, only one will take effect.

In addition, your SelectedItem declaration is probably wrong. SelectedItem="{Binding NAME}" will look for an item which is equal to the value of the NAME property of the ambient (probably Window-level) DataContext. This will work only if the ComboBox.ItemsSource is a list of strings. Since your ItemTemplate works, I assume ComboBox.ItemsSource is actually a list of City objects. But you are telling WPF that the SelectedItem should be a string (a NAME). This string will never be equal to any City object, so the result will be no selection.

So to fix the problem, after setting ItemsSource, set either SelectedItem or SelectedIndex, depending on your requirements and your data model:

cbo.ItemsSource = ser.GetCity().DefaultView;
cbo.SelectedIndex = 1;
// or: cbo.SelectedItem = "Wellington";    // if GetCity() returns strings - probably not
// or: cbo.SelectedItem = City.Wellington; // if GetCity() returns City objects
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!