Created
December 12, 2019 09:51
-
-
Save tluyben/c8bdfc27024e9ffe4453cbba7cf6ff06 to your computer and use it in GitHub Desktop.
Avalonia dynamic list (with Dictionary)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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