[英]Wp7 ListBox ItemSource ObservableCollection IndexOUtofRange and Items are not updated
[英]listbox.itemsource = null; throwing exception in wp7
我有一個列表框和一個文本框。 我想處理其keyup事件,但給我一個錯誤。
<ListBox Name="lstSelectedNumber" Height="50" MaxHeight="120" VerticalAlignment="Top" Grid.Column="1" SelectionChanged="lstSelectedNumber_SelectionChanged">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="Padding" Value="-15" />
<Setter Property="Margin" Value="0"/>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<toolkit:WrapPanel>
</toolkit:WrapPanel>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBox x:Name="txtNumber" Text="{Binding Name,Mode=TwoWay}" IsEnabled="{Binding IsEnabled,Mode=TwoWay}" Background="Transparent" Foreground="{StaticResource ContactSelectorBrush}" Style="{StaticResource DialNumberStyle}" FontSize="24" KeyUp="txtNumber_KeyUp">
<TextBox.CaretBrush>
<SolidColorBrush Color="{StaticResource CaretBrush}" />
</TextBox.CaretBrush>
</TextBox>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
private void txtNumber_KeyUp(object sender, KeyEventArgs e)
{
TextBox txtbox = sender as TextBox;
if (txtbox.Text.Contains(';'))
{
lstSelectedNumber.ItemsSource = null;
// My Application Got crashed at this point when i assign nullto item source
lstSelectedNumber.ItemsSource = lstContactModel;
}
我的更新集合是否是該列表框的itemsource,是否還有其他替代方法。 請告訴我任何解決方法。
那是因為它會觸發lstSelectedNumber_SelectionChanged
事件。 將調試器放在異常語句上並按F11鍵將帶您進入此事件。
更換
lstSelectedNumber.ItemsSource = null;
lstSelectedNumber.ItemsSource = lstContactModel;
與
lstSelectedNumber.SelectionChanged -= lstSelectedNumber_SelectionChanged;
lstSelectedNumber.ItemsSource = null;
lstSelectedNumber.ItemsSource = lstContactModel;
lstSelectedNumber.SelectionChanged += lstSelectedNumber_SelectionChanged;
我已自行修復此問題。 問題是這樣的,當我的文本框事件被調用時,它會對我的列表做一些更改並將空源綁定到我的列表框,並且這種更改會影響我的UI和UI無法處理該更改,因此我將所有代碼放入Dispatcher中,所以一旦做的事情反映了UI的變化,UI接受了
private void txtNumber_KeyUp(object sender, KeyEventArgs e)
{
TextBox txtbox = sender as TextBox;
if (txtbox.Text.Contains(';'))
{
Dispatcher.BeginInvoke(() =>
{
lstSelectedNumber.ItemsSource = null;
lstSelectedNumber.ItemsSource = lstContactModel;
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.