raphadko raphadko - 1 month ago 6
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}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Height="40" MinWidth="40" Content="{Binding Name}" Margin="2"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>


My code behind looks like this:

public MainWindow()
{
InitializeComponent();
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?

Answer

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}}}">
Comments