简体   繁体   中英

ComboBox ItemsSource binding doesn't update with Observable Collection Add

I have a simple wpf app, that I want to try to use ItemsSource binding from xaml. When I click the button. it should be updated also in the UI, but it doesn't.

Why doesn't it work?

Xaml code:

<Window x:Class="SendRawEthernetPacketsGUI.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
<Grid>
    <ComboBox HorizontalAlignment="Left" Margin="76,65,0,0" VerticalAlignment="Top" Width="120" ItemsSource="{Binding test}"/>
    <Button Content="Button" HorizontalAlignment="Left" Margin="90,171,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>

</Grid>

C# code:

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace SendRawEthernetPacketsGUI
{

/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
    public ObservableCollection<string> test = new ObservableCollection<string>();
    public Window1()
    {
        InitializeComponent();
        DataContext = this;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        test.Add("fdfddf");
    }
}
}

It feels kinda stupid to even ask this, but even looking in google didn't help me. So can you?

Your binding never worked in the first place. You can only bind to properties not fields .

Try this instead:

public ObservableCollection<string> test { get; set; }

public Window1()
{
    Test = new ObservableCollection<string>();
}

Or if you want some tricky C# 6 magic:

public ObservableCollection<string> test => new ObservableCollection<string>();

This is a function bodied-member and compiles to a read-only property that is initialized to the new ObservableCollection

Caveats/Design Errors:

Note that in both cases you aren't using INotifyPropertyChanged , so wholesale assignments to the collection won't be picked up by the UI. You should also be using PascalCase for your public properties, and using a proper view model instead of binding to the code-behind.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM