将组合框中的一个特定复选框和数据模板中的复选框设为默认复选框



我在数据模板中有带复选框的组合框。组合框ItemSource属性与ViewModel中的集合绑定。我想选中一个特定的复选框作为默认复选框。我该怎么做?

<ComboBox Grid.Column="1"
          ItemsSource="{Binding MyCollection, Mode=OneWay}" 
          Style="{StaticResource MyComboboxStyle}"
          Margin="5"
          MinWidth="120">
                <ComboBox.ItemTemplate>
                    <DataTemplate>            
                        <CheckBox Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}, Path=DataContext.MyCheckedCommand}"
                                  CommandParameter="{Binding RelativeSource={RelativeSource Self}}"
                                  Content="{Binding}"
                                  IsChecked="false"
                                  VerticalAlignment="Center"
                                  Margin="3"/>                    
                    </DataTemplate>
                </ComboBox.ItemTemplate>
            </ComboBox>

我会在视图模型中创建一个布尔属性,然后在加载集合时,在集合中找到应该检查的对象,并将其设置为true。

 public bool IsChecked { get; set; }

XAML:

  <CheckBox Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}, Path=DataContext.MyCheckedCommand}"
                              CommandParameter="{Binding RelativeSource={RelativeSource Self}}"
                              Content="{Binding}"
                              IsChecked="{Binding IsChecked}"
                              VerticalAlignment="Center"
                              Margin="3"/>

然而,这可能需要您将此属性与对象模型分开

最新更新