次の方法で共有


WPF ListBox.Items.Clear()で出る例外の解決法

質問

2016年9月29日木曜日 3:02

ListBoxの登録要素を全て削除したいと思っています。
下に提示したコードは正常に動作しますが、

<Window x:Class="MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
    <Grid>
        <ListBox Height="86" HorizontalAlignment="Left" Margin="121,75,0,0" Name="ListBox1" VerticalAlignment="Top" Width="131" >
            <ListBox>
                <ListBoxItem>000</ListBoxItem>
                <ListBoxItem>111</ListBoxItem>
            </ListBox>
        </ListBox>
        <Button Content="Button" Height="50" HorizontalAlignment="Left" Margin="314,125,0,0" Name="Button1" VerticalAlignment="Top" Width="102" />
    </Grid>
</Window>

'コード

Class MainWindow
    Private Sub Button1_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Button1.Click
        Me.ListBox1.Items.Clear()
    End Sub
End Class

現在作成中のプログラムでは、ListBox1に要素として追加したListBoxItems内の子要素にバインディングが設定してあったりと、少し複雑な使い方をしているのが理由なのか分かりませんが、実行中にMe.ListBox1.Items.Clear()で次の例外が発生します。

InvalidOperationExceptionはユーザーコードによってハンドルされませんでした。
ItemsSource が使用中の場合、操作は無効です。代わりに ItemsControl.ItemsSource を使用して要素にアクセスし、変更してください。

↑ これは何を言っているのか、理解できません。どうすれば例外を回避できるのか、御教授を御願い致します。

すべての返信 (3)

2016年9月29日木曜日 3:23 ✅回答済み

http://stackoverflow.com/questions/6882782/how-to-remove-all-item-in-listview-when-it-bindto-objectdataprovider

上の方と同じような現象なのかな?と思いました。

Me.ListBox1.Items.Clear()

の部分を

Me.ListBox1.ClearValue(ListBox.ItemsSourceProperty)

としてみて削除できますでしょうか?


2016年9月29日木曜日 4:09

Kenjinoteさん、御回答ありがとうございました。これで動作しました。

この質問をする前に、オブジェクトが使用中で消去できないという意味なのでListBox1.items(0)=Nothingとか、色々試してリンクを切り離してみたのですが、どうやっても解決できませんでした。

もしよろしかったら、どういうメカニズムでこういう例外が発生しているのか、解説していただけたら今後の学習の参考になります。

今回の御回答、誠にありがとうございました。


2016年9月29日木曜日 4:10

こんにちは。

ItemsSourceは一般的にはObservableCollectionをバインドしていることが多いと思うので
ClearValueで解除してしまうと後々に影響出ることがあるかもしれません。(ObservableCollectionを必ず再設定しているのであればいいのですが)

なので、ItemsSource自体のClear処理を呼び出したほうが良いと思います。
本来であればBindingSource側でClearするべきですが。

'Me.ListBox1.Items.Clear()
Dim list = TryCast(Me.ListBox1.ItemsSource, IList)
If list IsNot Nothing Then
    list.Clear()
End If