![](/img/trans.png)
[英]Why doesn't my view update when adding items to the ObservableCollection
[英]My ListBox doesn't update when deleting or adding items, despite data binding
我所有的數據綁定在整個應用程序中都有效。 我已經嘗試了數據綁定ItemsSource的每種模式。 該列表在開始時已加載,但是當我使用自己制作的上下文菜單時不會更新。 我已經對WriteLine
進行了測試,以確保其他所有功能都可以正常工作。
XAML
<ListBox Grid.Row="1" SelectionMode="Single" BorderThickness="0"
SelectionChanged="ListBox_SelectionChanged"
SelectedIndex="{Binding Path=Data.SelectedFeedIndex, Mode=TwoWay}"
SelectedItem="{Binding Path=Data.SelectedFeed, Mode=TwoWay}"
ItemsSource="{Binding Path=Data.Feeds}"
ScrollViewer.HorizontalScrollBarVisibility="Disabled">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<TextBlock Text="{Binding Path=Title}" MouseDown="TextBlock_MouseDown" />
<TextBox Text="{Binding Path=Title}"
Visibility="Collapsed" KeyDown="TextBox_KeyDown" Padding="1" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ContextMenu>
<ContextMenu>
<MenuItem Header="New" Command="{Binding Path=Data.NewFeed}" />
<MenuItem Header="Delete" Command="{Binding Path=Data.DeleteFeed}" />
</ContextMenu>
</ListBox.ContextMenu>
<ListBox.InputBindings>
<KeyBinding Key="Delete" Command="{Binding Path=Data.DeleteFeed}" />
</ListBox.InputBindings>
</ListBox>
物業
private List<Feed> _Feeds = new List<Feed>();
public List<Feed> Feeds
{
get
{
return _Feeds;
}
set
{
_Feeds = value;
onPropertyChanged("Feeds");
}
}
命令
public ICommand DeleteFeed
{
get
{
return new RelayCommand(ExecuteDeleteFeed, CanDeleteFeed);
}
}
public void ExecuteDeleteFeed(object parameter)
{
Feeds.RemoveAt(SelectedFeedIndex);
SelectedFeedIndex = nextIndex;
onPropertyChanged("Feeds");
}
public bool CanDeleteFeed(object parameter)
{
return Feeds.Count > 1;
}
我通過與上面的ListBox綁定來接收索引:
private int _SelectedFeedIndex;
public int SelectedFeedIndex
{
get
{
return _SelectedFeedIndex;
}
set
{
_SelectedFeedIndex = value;
onPropertyChanged("SelectedFeedIndex");
}
}
編輯
我嘗試更改為ObservableCollection
,但是出現以下錯誤。
System.Windows.Data Error: 40 : BindingExpression path error: 'Feeds' property not found on 'object' ''Library' (HashCode=60811181)'. BindingExpression:Path=Data.Feeds; DataItem='MainViewModel' (HashCode=34760343); target element is 'ListBox' (Name=''); target property is 'ItemsSource' (type 'IEnumerable')
System.Windows.Data Error: 40 : BindingExpression path error: 'Feeds' property not found on 'object' ''Library' (HashCode=60811181)'. BindingExpression:Path=Data.Feeds; DataItem='MainViewModel' (HashCode=34760343); target element is 'ComboBox' (Name=''); target property is 'ItemsSource' (type 'IEnumerable')
新物業
ObservableCollection<Feed> Feeds = new ObservableCollection<Feed>();
哦好的。 我把它變成了財產。 現在可以使用了。 非常感謝。 我以為,如果您沒有為所有屬性手動使用INotifyProperty,則只需要ObservableCollection。 現在有道理了。
您需要將List更改為ObservableCollection,因為List類不會生成事件來通知其內容已更改。 結果,列表框將顯示列表的初始內容,但之后再也不會更新。 ObservableCollection確實會生成更改事件,並將執行您需要的操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.