[英]MVVM Binding SelectedIndex of ComboBox, Combobox uses a ControlTemplate, Binding does not work
我有一些組合框並使用 ControlTemplate 用字母“AZ”填充它們。 我想將 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 來用字母“AZ”填充 ComboBox。 只需使用 ItemsSource:
<ComboBox x:Name="comboBoxL1Pos"
Grid.Column="1" Grid.Row="4"
ItemsSource="{Binding Source='ABCDEF..XYZ'}"
SelectedIndex="{Binding Selectedindex}"/>
SelectedIndex 的 TemplateBinding 不起作用,因為它是單向的。 請參閱問題: 在 WPF 中,為什么 TemplateBinding 在 Binding 起作用的地方不起作用?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.