I was trying create some UI elements in my WPF application. I took this example: WPF: How to dynamically Add Controls in dynamically created WPF Window as reference. But, my interface was a mess. You can see by image below:
This is the code that got the JSON
:
public MainWindow()
{
InitializeComponent();
db = new DbItens("DBItens");
using (var webClient = new WebClient())
{
var get = JsonConvert.DeserializeObject<RootJson>(Encoding.UTF8.GetString(webClient.DownloadData(url)));
foreach (var item in get.Itens)
{
buildForm(item, prox);
prox++;
}
}
}
And this is my buildForm
method:
private void buildForm(Item item, int prox)
{
stkSPanel.Orientation = Orientation.Vertical;
stkSPanel.Children.Add(new Label
{
Content = item.Nome,
});
stkSPanel.Children.Add(new TextBlock
{
Text = item.Descricao,
});
Image img = new Image
{
Height = 100,
Width = 100
};
img.Source = new BitmapImage(new Uri(item.Foto));
StackPanel panel = new StackPanel();
panel.Orientation = Orientation.Horizontal;
panel.Margin = new Thickness(10);
panel.Children.Add(img);
stkSPanel.Children.Add(new Button {Content = panel });
}
How i can format this elements?
Note: My code need to be that way (not directly implemented in XAML), because i will get new items from database too (I only have the stackPanel
in XAML), and i need show then by heapsort algorithm
.
XAML Code:
<Window x:Class="BlueGearAPP.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:BlueGearAPP"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525" ScrollViewer.CanContentScroll="True" ScrollViewer.HorizontalScrollBarVisibility="Auto">
<ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto">
<StackPanel x:Name="stkSPanel"></StackPanel>
</ScrollViewer>
I want something like this:
ANSWER
Talking with sumodh-s i've been changed my panels orientation to vertival, and my UI controls to horizontal with alignment in center. And now it's worked fine.