user3363744 user3363744 - 3 months ago 14
C# Question

Simple ObservableCollection binding ? Can't wrap my brain around it

I want to bind a listbox to a simple observablecollection

XAML - Binding Listbox to my Observablecollection object

<Window x:Class="ObservableCollection.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:ObservableCollection"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ListBox Name="Listbox1" ItemsSource="{Binding Path= Test, UpdateSourceTrigger=PropertyChanged}"></ListBox>
</Grid>




Adding a few items and trying to display the data in the listbox

namespace ObservableCollection
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
ObservableCollection<int> Test = new ObservableCollection<int>();
Listbox1.DataContext = Test;
Test.Add(1);
Test.Add(123232);
}
}
}


The data doesnt show up when running the code. What am I doing wrong here?

Thank you

Answer

A binding expression will either include a property path, in which case the path must refer to a public property that exists on the DataContext object, or it will omit the path, in which case the binding will be to the DataContext object yourself.

In your example, you appear to be confusing the two. You configure the binding as if you want to omit the property path, but then in the XAML you provide a property path.

You can do one of the following…

Add a property to your MainWindow class and keep the path you have in the XAML:

public partial class MainWindow : Window
{
    public ObservableCollection<int> Test { get; set; }

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

Or, you can change your XAML to use the DataContext object directly:

<Window x:Class="ObservableCollection.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:ObservableCollection"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">

    <Grid>
        <ListBox Name="Listbox1" ItemsSource="{Binding}"/>
    </Grid>
</Window>

Note that you also don't need to set the UpdateSourceTrigger property. The target value isn't ever going to change, so there's no reason to worry about how the source might be updated in such an event.

Comments