我希望能够将ListBox
绑定到List<>
或ObservableCollection<>
,并且能够在保持绑定的同时更改列表本身。
在ViewModel中:
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChangedEvent(string propertyName) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
private ObservableCollection<string> items = new ObservableCollection<string>();
public ObservableCollection<string> Items
{
get
{
return items;
}
set
{
items = value;
RaisePropertyChangedEvent(nameof(Items));
}
}
private void FillItems()
{
Items1 = new ObservableCollection<string>();
Items.Add("1");
Items.Add("2");
}
在视图中:
<ListBox x:Name="listBox" ItemsSource="{Binding Items}"/>
现在,当我调用FillItems()
函数时,列表不会显示项目。但如果我改变下面的代码,它将起作用:
private void FillItems()
{
Items.Clear();
Items.Add("1");
Items.Add("2");
}
答案 0 :(得分:1)
确保视图模型实现INotifyPropertyChanged
并在目标属性发生更改时通知视图。
使用以下简单视图
<Window x:Class="WpfApplication1.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:WpfApplication1"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid >
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<ListBox x:Name="listBox" ItemsSource="{Binding Items}"/>
<Button Grid.Row="1" Content="Fill" Click="Button_Click" />
</Grid>
</Window>
以下代码和视图模型
namespace WpfApplication1 {
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window {
private MainViewModel viewModel;
public MainWindow() {
InitializeComponent();
viewModel = new MainViewModel() {
Items = new List<string>() {
"a", "b"
}
};
this.DataContext = viewModel;
}
private void Button_Click(object sender, RoutedEventArgs e) {
viewModel.FillItems();
}
}
public class MainViewModel : INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChangedEvent(string propertyName) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
Random random = new Random();
private List<string> items = new List<string>();
public List<string> Items {
get {
return items;
}
set {
items = value;
RaisePropertyChangedEvent(nameof(Items));
}
}
public void FillItems() {
var list = Enumerable.Range(0, 10).Select(i => random.Next(100).ToString()).Distinct().ToList();
Items = new List<string>(list);
}
}
}
每次点击该按钮时,ListBox
和List
都会按预期更新ObservableCollection
。
您应该再次检查您的代码,并确保遵循可能影响您的代码的常见做法,因为您在示例中提供的内容应该有效。