San Dy
San Dy

Reputation: 27

How to set SelectedIndex?

I have tried to set the SelectedIndex property to 0 so that "Read" shows up when the user control renders, but it is not working. It doesn't show anything, but when I click on the combo box, I do see all my items.

Is there something I'm missing?

My XAML code:

<ComboBox SelectedIndex="0" Grid.Row="1" Grid.ColumnSpan="2" Text="{Binding Path=DataMode}">
    <ComboBoxItem Content="Read"></ComboBoxItem>
    <ComboBoxItem Content="Subscribe"></ComboBoxItem>
</ComboBox>

Upvotes: 1

Views: 109

Answers (1)

Sham
Sham

Reputation: 930

Text property binding is overriding the selection.

Approach 1 - Change the binding Mode to OneWayToSource if you don't want to set Combobox item from VM.

 <ComboBox SelectedIndex="0" Grid.Row="1" Grid.ColumnSpan="2" Text="{Binding Path=DataMode, Mode=OneWayToSource}">
        <ComboBoxItem Content="Read"></ComboBoxItem>
        <ComboBoxItem Content="Subscribe"></ComboBoxItem>
    </ComboBox>

Approach 2 - Remove SelectedIndex from xaml and set Text through property.

 <ComboBox Grid.Row="1" Text="{Binding Path=DataMode}" Grid.ColumnSpan="2" Height="20" Width="100" >
        <ComboBoxItem Content="Read"></ComboBoxItem>
        <ComboBoxItem Content="Subscribe"></ComboBoxItem>
    </ComboBox>

In VM -

private string dataMode;
    public string DataMode
    {
        get
        {
            if (string.IsNullOrEmpty(dataMode))
            {
                return "Read";
            }

            return dataMode;
        }
        set
        {
            dataMode = value;
            RaisePropertyChanged("DataMode");
        }
    }

Upvotes: 1

Related Questions