I'm trying to dynamicly add items (textbox and button) into a listbox.
This is my xaml
:
<ListBox x:Name="projects_list" Height="459" Canvas.Left="20" Canvas.Top="86" Width="755">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical" Height="42">
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
And, in the StackPanel
I want to have my 2 buttons.
Inside a foreach
, I create the buttons like this:
items.ForEach(delegate (Projects project)
{
Button txt = new Button(); // NAME
txt.Height = 32;
txt.Width = 320;
txt.Content = project.name;
Button gen_token = new Button();
gen_token.Height = 26;
gen_token.Width = 180;
gen_token.Content = "Generate";
this.projects_list.Items.Add(txt);
this.projects_list.Items.Add(gen_token);
}
But, When I add the elements into my ListBox
, nothing appears. Even though, there is a good number of StackPanel
s in my list.
Any idea? Thanks!
EDIT : If I Had
<Button Content="{Binding}" ></Button>
Into the stackPanel
, My buttons are showing, but not really has I want to, they are one by stackpanel
and I want both buttons on every panel ..
EDIT 2 : So, I tried this :
public List<Dictionary<string, Button>> Items { get; set; }
....
Items = new List<Dictionary<string, Button>>();
DataContext = this;
And later in the each
Dictionary<string, Button> dict = new Dictionary<string, Button>() { { "name", txt }, { "token", gen_token } };
Items.Add(dict);
So In my xaml, I have :
<ListBox x:Name="projects_list" Height="459" Canvas.Left="20" Canvas.Top="86" Width="755" ItemsSource="{Binding Items}" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical" Height="42">
<Button Content="{Binding Path=name}" ></Button>
<Button Content="{Binding Path=token}" ></Button>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
But still, nothing appears :(
A quick example:
Window.Xaml
<ListBox ItemsSource="{Binding Items}">
<ListBox.ItemTemplate>
<DataTemplate>
<Button Content="{Binding}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Code behind
public partial class MainWindow : Window
{
public ObservableCollection<string> Items { get; set; }
public MainWindow()
{
InitializeComponent();
Items = new ObservableCollection<string> { "Item 1", "Item2" };
DataContext = this;
}
}
This is just a quick example to give you an idea. You would probably do a ViewModel instead of code behind.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.