Skip to content

Instantly share code, notes, and snippets.

@tluyben
Created December 12, 2019 09:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tluyben/c8bdfc27024e9ffe4453cbba7cf6ff06 to your computer and use it in GitHub Desktop.
Save tluyben/c8bdfc27024e9ffe4453cbba7cf6ff06 to your computer and use it in GitHub Desktop.
Avalonia dynamic list (with Dictionary)
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
using System.Collections.Generic;
using System.Linq;
using Avalonia.Data;
using Avalonia.Controls.Templates;
namespace Playground
{
public class ListItem
{
public string Greet { get; set; }
public string Something { get; set; }
public override string ToString()
{
return $"{Greet} {Something}";
}
}
public class ListView : Window
{
public ListView()
{
InitializeComponent();
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
// Let's build up the content with normal model classes;
var modelList = new List<ListItem>()
{
new ListItem { Greet = "Hello", Something = "World" },
new ListItem { Greet = "Hi", Something = "Earth" },
new ListItem { Greet = "Howdy", Something = "Planet" }
};
// Create a List of Dictionaries from that:
var dictList = modelList.Select(i => i.GetType().GetProperties().ToDictionary(t => t.Name, t => t.GetValue(i).ToString())).ToList();
// Create a base panel
StackPanel mainStack = new StackPanel
{
Orientation = Orientation.Vertical
};
Content = mainStack;
// Create the list;
var listView = new ListBox
{
};
mainStack.Children.Add(listView);
// create a datatemplate:
var template = new FuncDataTemplate<Dictionary<string, string>>(x =>
{
var stack = new StackPanel
{
Orientation = Orientation.Horizontal
};
stack.Children.Add(new TextBlock
{
[!TextBlock.TextProperty] = new Binding("[Greet]")
}
);
stack.Children.Add(
new TextBlock
{
[!TextBlock.TextProperty] = new Binding("[Something]")
}
);
return stack;
});
// assign it
listView.ItemTemplate = template;
// now connect the items
listView.Items = dictList;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment