2

I am developing a Windows Phone 8 App in which I am using a checkbox inside a listbox along with some textblocks.

<ListBox x:Name="lstStudentSelect"  ItemContainerStyle="{StaticResource ListBoxItemStyle1}" Background="Transparent" ScrollViewer.VerticalScrollBarVisibility="Visible" Height="487" BorderThickness="0"  VerticalAlignment="Top" Margin="8,198,10,0">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel   Orientation="Horizontal">
                <StackPanel Width="360" Orientation="Horizontal" HorizontalAlignment="Left">
                    <TextBlock Text="{Binding stunum}" Width="80"   Foreground="Black"  TextWrapping="Wrap"  FontSize="20" VerticalAlignment="Center" />
                    <TextBlock  Text="{Binding name}" Width="280"  Foreground="Black"  TextWrapping="Wrap"  FontSize="20" VerticalAlignment="Center" />
                </StackPanel>
                <StackPanel Width="5"></StackPanel>
                <StackPanel Width="150" Orientation="Horizontal" HorizontalAlignment="Right">
                    <CheckBox  IsChecked="{Binding ChkFlag, Mode=TwoWay}"  BorderBrush="#203485" Foreground="Black" BorderThickness="1" Tag="{Binding cusnum}" Name="cusCheck" Checked="cusCheck_Checked_2" Unchecked="cusCheck_Unchecked_2" ></CheckBox>
                    <TextBlock Text=" "  TextWrapping="Wrap" Foreground="Black" FontSize="20" VerticalAlignment="Center" />
                </StackPanel>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

when I check/select on the checkbox the checkbox checked event fires, when I uncheck/unselect a checkbox the checkbox unchecked event fires.

But now my issue is :

When I am scrolling the listbox the checkbox checked and unchecked event fires automatically ?

How can I avoid this to happen ?

4

2 回答 2

1

您的问题与您正在绑定IsChecked属性并具有CheckedUnchecked事件的处理程序有关。当绑定更新并且属性更改时,这将导致事件触发。

ItemsSource设置/加载时将为每个项目触发事件。

默认情况下ListBox,它的项目面板使用虚拟化容器。这意味着当您滚动时,项目将被加载进出容器,并且这也将由于绑定更改而触发事件。这就是为什么您会在滚动时看到更多事件被触发的原因。(假设您有足够大的列表需要虚拟化。)

假设这ChkFlag是您的 ViewModel 上的一个属性,并且cusCheck_Checked_2&cusCheck_Unchecked_2是您视图上的事件处理程序,您可以通过将逻辑从事件处理程序移动到 setter for 来使事情变得更简单并避免这个问题ChkFlag。(这也可能会提高可测试性的易用性。)

例如,您可以拥有这样的属性:

    public bool ChkFlag
    {
        get
        {
            return this.chkFlagField;
        }

        set
        {
            if (this.chkFlagField != value)
            {
                this.chkFlagField = value;
                this.RaisePropertyChanged();

                if (value)
                {
                    // perform checked action
                }
                else
                {
                    // perform unchecked action
                }
            }
        }
    }
于 2013-07-18T08:38:07.123 回答
0

另一种解决方案可以将 StackPanel 设置为 Panel。

<ListBox.ItemsPanel>
    <ItemsPanelTemplate>
        <StackPanel/>
    </ItemsPanelTemplate>
</ListBox.ItemsPanel>
于 2017-05-31T11:32:34.200 回答