user2348001
user2348001

Reputation: 45

WPF - Observable collection binding error

I am tring to create a simple program that connect ObservableCollection to ListBox. I wrote:

public ObservableCollection<int> Values { get; set; }

and

public MainWindow()
{
    InitializeComponent();
    Values = new ObservableCollection<int>();
    Values.Add(1);
    DataContext = this;
}

then I was created button and wrote:

public Button1_Clicke(object sender, RoutedEventArgs e)
{
    Values.Add(2);
}

XMAL:

<ListBox x:Name="list" ItemsSource="{Binding Path=Values}"/>

When the window opened I able to see the '1' value. But when I clicked the button, The list box dosent update the items. What is wrong?

Upvotes: 0

Views: 883

Answers (1)

Toan Vo
Toan Vo

Reputation: 1308

You can try this:

<ListBox x:Name="list" ItemsSource="{Binding Path=Values}"/>

EDIT: I have made a simple sample as below:

<Window x:Class="WpfApplication1.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">
    <StackPanel>

        <ListBox x:Name="list" ItemsSource="{Binding Path=Values}"/>
        <Button Click="Button_Click" Content="Test"></Button>
    </StackPanel>

</Window>

Code behind (Window1.xaml.cs)

using System.Collections.ObjectModel;

/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
    public ObservableCollection<int> Values { get; set; }

    public Window1()
    {
        InitializeComponent();

        Values = new ObservableCollection<int>();
        Values.Add(1);
        DataContext = this;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        Values.Add(2);
    }
}

It is working as expected. So base on your comments below why don't you try remove all of converter to make sure it correct or not.

Upvotes: 2

Related Questions