在 Windows phone 中获取复选框索引

Getting Checkbox index in Windows phone

我有一个列表框,其中包含一个文本块和另一个复选框。 在 xaml 文件中,它看起来像这样:

<ListBox x:Name="notificationSettingsListBox" Grid.Row="1"   Margin="20,20,20,20" Background="#e79e38" SelectionChanged="notificationSettingsListBox_SelectionChanged" Tap="notificationSettingsListBox_Tap">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Grid Background="#055cc3" Width="500" Height="200" Margin="30,40,30,20">
                    <StackPanel Orientation="Vertical">
                        <TextBlock Text="{Binding channel_name}" Foreground="White" FontSize="31" TextAlignment="Left" TextWrapping="Wrap" Margin="0,20,10,0" />
                        <CheckBox Name="pushNotiOnCheckBox" Content="Enable Notification" IsChecked="false" Foreground="White" Background="White" BorderBrush="White" Checked="pushNotiOnCheckBox_Checked" Unchecked="pushNotiOnCheckBox_Unchecked"/>
                    </StackPanel>

                </Grid>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

现在,每当用户选中任何复选框时,我都需要该复选框的索引。 我想要这个方法内部的索引:

private void pushNotiOnCheckBox_Checked(object sender, RoutedEventArgs e)
        {}

如何在 Windows phone 中实现?

您可以使用 ItemContainer 样式来做到这一点。

<ListBox SelectedIndex={Binding Index,Mode=Twoway}>
    <ListBox.ItemContainerStyle>
          <Style TargetType="ListBoxItem">
                    <Setter Property="IsSelected"
                            Value="{Binding IsOperationSelected,Mode=TwoWay}" />
           </Style>
      </ListBox.ItemContainerStyle>
</ListBox>

并且您需要将 CheckBox.IsChecked 更改为 Binding Like this

<CheckBox Name="pushNotiOnCheckBox" Content="Enable Notification" IsChecked="{Binding IsOperationSelected,Mode=TwoWay}" Foreground="White" Background="White" BorderBrush="White" Checked="pushNotiOnCheckBox_Checked" Unchecked="pushNotiOnCheckBox_Unchecked"/>

假设你在ListBox.ItemsSource中有List<T>,那么你可以使用IndexOf()方法获取ItemsSource中底层模型的索引,对应到 ListBoxCheckBox 的索引:

private void pushNotiOnCheckBox_Checked(object sender, RoutedEventArgs e)
{
    //get the checkbox that corresponds to current checked event
    CheckBox chk = (CheckBox)sender;
    //get the underlying model object from DataContext
    MyModel model = (MyModel)chk.DataContext;
    //get the entire models used to populate the ListBox
    var models = (List<MyModel>)notificationSettingsListBox.ItemsSource;
    //find index of current model in the models list,
    //which should be the same as checkbox index you want
    var index = models.IndexOf(model);
}