[英]How to remove objects from a list bound to an ObservableCollection in C# MVVM
[英]Remove data from a bound list C#
我目前正在嘗試從綁定列表中刪除項目。
這是它在xaml中的綁定位置。
<ListBox Height="362" HorizontalAlignment="Left" Margin="6,245,0,0" Name="lstHoldCategories" VerticalAlignment="Top" Width="462" SelectionChanged="list_SelectionChanged_1" BorderThickness="0,0,0,0">
<ListBox.ItemTemplate>
<DataTemplate>
<!--This positions the Text eg name etc-->
<StackPanel Orientation ="Vertical">
<!--This changes the size of the photo on the left-->
<Image Width="445" Height="300" HorizontalAlignment="Center" Stretch="UniformToFill" >
<Image.Source>
<BitmapImage UriSource="{Binding imgSource}"/>
</Image.Source>
</Image>
<TextBlock Text="{Binding Name}" Style="{StaticResource PhoneTextLargeStyle}" Width="1000" />
<TextBlock Text="{Binding Type}" Style="{StaticResource PhoneTextLargeStyle}" Width="1000" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
然后,我制作了一個單獨的通用列表,將其保存在單獨的未綁定listBox中,以便我可以選擇“類型”並加載該類型的所有動物。
這是我設置未綁定列表的代碼
public CategorySearch()
{
InitializeComponent();
observablePets = new ObservableCollection<Shop>();
temp = new ObservableCollection<Shop>();
MyList.Add("Dog");
MyList.Add("Cat");
MyList.Add("Fish");
MyList.Add("Lizard");
lstCategory.ItemsSource = MyList;
}
這是我完成未綁定listBox的SelectedIndex的步驟,以添加所選“類型”的動物
private void lstCategory_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (lstCategory.SelectedIndex == 0)
{
foreach (Shop pet in thisApp.myshop)
{
if (pet.Type == "Dog")
{
//lstHoldCategories.Items.Clear();
temp.Add(pet);
lstHoldCategories.ItemsSource = temp;
}
}
}
if (lstCategory.SelectedIndex == 1)
{
foreach (Shop pet in thisApp.myshop)
{
if (pet.Type == "Cat")
{
//lstHoldCategories.Items.Clear();
temp.Add(pet);
lstHoldCategories.ItemsSource = temp;
}
}
}
if (lstCategory.SelectedIndex == 2)
{
foreach (Shop pet in thisApp.myshop)
{
if (pet.Type == "Fish")
{
//lstHoldCategories.Items.Clear();
temp.Add(pet);
lstHoldCategories.ItemsSource = temp;
}
}
}
if (lstCategory.SelectedIndex == 3)
{
foreach (Shop pet in thisApp.myshop)
{
if (pet.Type == "Lizard")
{
//lstHoldCategories.Items.Clear();
temp.Add(pet);
lstHoldCategories.ItemsSource = temp;
}
}
}
}
如您在這段代碼中所看到的,我已經注釋掉了一段代碼,我相信這將清空selectedIndex上的listBox並用新的選擇重新加載listBox。 不幸的是,當您選擇索引時,它不起作用並使應用程序崩潰。
如果有另一種方法可以清空綁定的listBox,我將不勝感激有人建議我如何做,在此先感謝Jason
//// Pics \\\\這是選擇索引之前頁面的外觀
這是選擇索引時綁定的listBox的外觀
您需要清除集合本身,而不是綁定到集合的對象。 快速搜索顯示了此內容... 從listobox刪除所有項目
為了澄清起見,Items集合位於ListBox上,並且該屬性為只讀。 因此,您需要從ListBox實際綁定到的集合中刪除項目。
您應該能夠在添加新項目之前臨時調用clear。 但是,您需要確保您的集合源實現了INotifyCollectionChanged才能查看反映在UI中的更改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.