Martin
Martin

Reputation: 41

MVVM Binding SelectedIndex of ComboBox, Combobox uses a ControlTemplate, Binding does not work

I have some comboboxes and use a ControlTemplate to fill them with the Leters "A-Z". I want to bind the SelectedIndex Property to my ViewModel. The binding works fine if I dont use the Template. If I use it, however, the binding does not work.

Here comes my xaml:

<Window.DataContext>
    <local:MainWindowViewModel/>
</Window.DataContext>
<Window.Resources>
    <ControlTemplate x:Key="comoboxABC" TargetType="ComboBox">
        <Grid>
            <ComboBox >
                <ComboBoxItem Content="A"/>
                <ComboBoxItem Content="B"/>
                ...
                <ComboBoxItem Content="Z"/>
            </ComboBox>
        </Grid>
    </ControlTemplate>
</Window.Resources>
<Grid>
    <ComboBox Template="{StaticResource comoboxABC}" x:Name="comboBoxL1Pos" Grid.Column="1" Grid.Row="4" 
                      SelectedIndex="{Binding Selectedindex}"/>
</Grid>

My ViewModel:

public class MainWindowViewModel : BaseViewModel
{
    private int selectedindex;

    public int Selectedindex
    {
        get => selectedindex;
        set
        {
            selectedindex = value;
            OnPropertyChanged(nameof(Selectedindex));
        }
    }
}

I tried to use TemplateBinding in my ControlTemplate

<Window.Resources>
    <ControlTemplate x:Key="comoboxABC" TargetType="ComboBox">
        <Grid>
            <ComboBox SelectedIndex="{TemplateBinding SelectedIndex}">
                <ComboBoxItem Content="A"/>

This didn't work as well. Can you please help me with this problem?

Upvotes: 1

Views: 184

Answers (1)

ASh
ASh

Reputation: 35646

you don't need ControlTemplate to fill ComboBox with letters "A-Z". Just use ItemsSource:

<ComboBox x:Name="comboBoxL1Pos"
          Grid.Column="1" Grid.Row="4"
          ItemsSource="{Binding Source='ABCDEF..XYZ'}"
          SelectedIndex="{Binding Selectedindex}"/>

TemplateBinding for SelectedIndex doesn't work because it is OneWay. see the question: In WPF, why doesn't TemplateBinding work where Binding does?

Upvotes: 1

Related Questions