gpt4 book ai didi

c# - 为什么 ListView 在 MVVM 中不更新

转载 作者:行者123 更新时间:2023-12-03 11:03:32 29 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





WPF ListView: Changing ItemsSource does not change ListView

(7 个回答)


5年前关闭。




我有一个小问题,我不明白它来自哪里,我想当我得到答案时,我可能会说著名的“aaaaahhhhh yessss!当然!”所以这是我的问题:我尝试更新 listView在 mvvm 中,通过拖放,我可以看到 List<string>进入listView已更新,里面有一个新项目,我传递给 listView 的元素项目,但 View 不会更新,新项目也不会出现。这是我的代码:

private List<string> _listViewItems;
public List<string> listViewItems
{
get
{
return _listViewItems;
}
set
{
_listViewItems = value;
OnPropertyChanged("listViewItems");
}
}

public ICommand MouseMove { get; set; }

//in constructor
MouseMove = new BaseCommand(GoMouseMove);

private void GoMouseMove(object obj)
{
MouseEventArgs e = (MouseEventArgs)obj;
try
{
if (e.LeftButton == MouseButtonState.Pressed)
{
draggedItem = (TreeViewItem) SelectedItem;
if (draggedItem != null)
{
DragDropEffects finalDropEffect = DragDrop.DoDragDrop(SelectedItem, SelectedItem, DragDropEffects.Move);

//Checking target is not null and item is dragging(moving)
if ((finalDropEffect == DragDropEffects.Move))
{
CopyItem(draggedItem, _target);
_target = null;
draggedItem = null;
}
}
}
}
catch (Exception)
{
}
}

private void CopyItem(TreeViewItem _sourceItem, ListViewItem _targetItem)
{
//Asking user wether he want to drop the dragged TreeViewItem here or not
if (MessageBox.Show("Would you like to drop " + _sourceItem.Header.ToString(), "", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
{
try
{
List<string> items = listViewItems;
items.Add(_sourceItem.Header.ToString());
listViewItems = items;
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
}

当我调试时,我得到了:

enter image description here
<ListView Name="listview1"
Grid.ColumnSpan="2"
Width="auto"
Height="auto"
Grid.Row="1"
AllowDrop="True"
ItemsSource="{Binding listViewItems, Mode=TwoWay}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Drop" >
<cmd:EventToCommand Command="{Binding Drop}"
PassEventArgsToCommand="True" />
</i:EventTrigger>
</i:Interaction.Triggers>
</ListView>

所以我们可以看到 algo.pdf已添加,但 View 不会更新。我错过了什么?!

非常感谢你 !

最佳答案

一个 List<>无法通知 WPF 已添加项目,因此 WPF 无法更新 UI 以显示任何添加的项目。

尝试使用 ObservableCollection<>当您添加/删除项目时,它将向 WPF 发送通知事件。

另外,请记住您的集合中的项目也应该实现 INotifyPropertyChanged如果您希望 WPF 在这些对象内的属性更改时更新。

关于c# - 为什么 ListView 在 MVVM 中不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42435181/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com