在Windows phone中获取复选框索引

本文关键字:复选框 索引 获取 Windows phone | 更新日期: 2023-09-27 18:07:24

我有一个列表框,其中包含一个文本块和另一个复选框。在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中实现这一点?

在Windows phone中获取复选框索引

假设您在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);
}

您可以使用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,就像这样

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