raphadko raphadko - 4 months ago 23
C# Question

Bound to WrapPanel but not updatind in WPF C#

I want to build a dynanmic list of buttons (or whatever element is in the template, doesn't really matter.., my XAML is:

<Button Content="Add New Button" VerticalAlignment="Center" Click="AddNewButton" HorizontalAlignment="Center"/>
<ItemsControl ItemsSource="{Binding ButtonsList}">
<Button Height="40" MinWidth="40" Content="{Binding Name}" Margin="2"/>

My code behind looks like this:

public MainWindow()
ButtonsList = new ObservableCollection<ShortcutButton>();


public class ShortcutButton
public string Name { get; set; }

public ObservableCollection<ShortcutButton> ButtonsList { get; set; }

private void AddNewButton(object sender, RoutedEventArgs e)
tblock.Text += "Button Clicked" + Environment.NewLine;
ButtonsList.Add(new ShortcutButton() { Name = "New button title" });

When I debug, I can see that objects are being added to the ButtonsList Observable Collection, but it does not update in the bound WrapPanel in ItemsControl.. What am I doing wrong?


Your Binding is incorrect, by default it will try to search for a property named ButtonList in the DataContext. To bind your ItemsSource to your ButtonList defined in the MainWindow you should change the RelativeSource like this:

<ItemsControl ItemsSource="{Binding Path=ButtonsList, RelativeSource={RelativeSource AncestorType={x:Type local:MainWindow}}}">