MVVM绑定ComboBox的SelectedIndex,Combobox使用了一个ControlTemplate,Binding不起作用

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

我有一些组合框并使用 ControlTemplate 用字母“A-Z”填充它们。 我想将 SelectedIndex 属性 绑定到我的 ViewModel。 如果我不使用模板,绑定工作正常。但是,如果我使用它,绑定将不起作用。

我的 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>

我的视图模型:

public class MainWindowViewModel : BaseViewModel
{
    private int selectedindex;

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

我尝试在我的 ControlTemplate 中使用 TemplateBinding

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

这也不起作用。 你能帮我解决这个问题吗?

您不需要 ControlTemplate 来用字母“A-Z”填充 ComboBox。只需使用 ItemsSource:

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

SelectedIndex 的 TemplateBinding 不起作用,因为它是单向的。看问题:In WPF, why doesn't TemplateBinding work where Binding does?