gpt4 book ai didi

c# - ListView 未使用绑定(bind)列表更新

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

我正在尝试实现一个简单的应用程序:我的 ViewModel 中有一个对象列表,我想在带有数据模板的 ListView 中显示。在我添加一个在列表中添加元素的按钮之前,一切都适用于绑定(bind)。当我这样做时, ListView 不会更新。但是,如果我尝试在列表中向下滚动,整个程序会停止并出现以下消息:

"The application is in break mode, Your app has entered a break state, but there is no code to show because all threads were executing external code (typically system or framework code)."



这是代码:
型号类:
namespace WpfTest
{
class Model
{
public string Value1 { get; set; }
public int Value2 { get; set; }
public bool Value3 { get; set; }

public Model()
{
Value1 = "abc";
Value2 = 3;
Value3 = true;
}
}
}

View 模型类:
namespace WpfTest
{
class ViewModel : INotifyPropertyChanged
{
public List<Model> _model;
private ICommand _addElement;

public ViewModel()
{
_addElement = new RelayCommand(Add);
_model = new List<Model>()
{
new Model(),
new Model()
};
}

public List<Model> ModelList
{
get => _model;
set => _model = value;
}

public ICommand AddElement
{
get => _addElement;
set => _addElement = value;
}

public void Add(object o)
{
_model.Add(new Model());
OnPropertyChanged("ModelList");
}

public event PropertyChangedEventHandler PropertyChanged;

public void OnPropertyChanged(string message)
{
if(PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(message));
}
}
}
}

XAML View :
<Window x:Class="WpfTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfTest"
xmlns:Mod="clr-namespace:WpfTest"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<DataTemplate DataType="{x:Type Mod:Model}">
<StackPanel Orientation="Horizontal">
<Label Content="{Binding Value1}"></Label>
<Label Content="{Binding Value2}"></Label>
<Label Content="{Binding Value3}"></Label>
</StackPanel>
</DataTemplate>
</Window.Resources>
<StackPanel>
<Button Command="{Binding AddElement}">Add</Button>
<ListView ItemsSource="{Binding ModelList}"></ListView>
</StackPanel>
</Window>

我正在使用最新版本的 Visual Studio Community 2017

在此先感谢您的帮助

最佳答案

替换 List<Model>ObservableCollection<Model> .当列表的内容发生更改时,这将正确通知任何绑定(bind)的 UI 元素。

如果您希望在 UI 中反射(reflect)对单个模型对象的更新,则模型类必须实现 INotifyPropertyChanged ,并且相应地更新了属性定义。

关于c# - ListView 未使用绑定(bind)列表更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48680748/

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