I want to create a listbox that contains buttons, and each time one button is selected (animation) my code is like this:
<UserControl x:Class="sa.UserControl2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="108" d:DesignWidth="592" xmlns:my="clr-namespace:sa">
<Grid Width="572">
<ListBox Name="ListBoxV" ScrollViewer.HorizontalScrollBarVisibility="Hidden"
Height="96" HorizontalAlignment="Left" VerticalAlignment="Top"
Width="572"
ItemsSource="{Binding ListItems}" >
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="Padding" Value="30 0 30 0" />
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
</Grid>
</UserControl>
public UserControl2()
{
InitializeComponent();
List<Temp> ListItems = new List<Temp>();
for (int i = 0; i < 20; i++)
{
ListItems.Add(new Temp("a"+i));
}
ListBoxV.ItemsSource = ListItems;
DispatcherTimer dt = new DispatcherTimer();
dt.Tick += new EventHandler(dt_Tick);
dt.Interval = TimeSpan.FromSeconds(2);
dt.Start();
}
void dt_Tick(object sender, EventArgs e)
{
if ((ListBoxV.SelectedIndex + 1) < ListBoxV.Items.Count)
ListBoxV.SelectedIndex = ListBoxV.SelectedIndex + 1;
else
ListBoxV.SelectedIndex = 0;
ListBoxV.ScrollIntoView(ListBoxV.SelectedItem);
}
public class Temp
{
public Temp(string s)
{Button b = new Button();
b.Name=s; }
}
}
The listbox don’t display buttons, only the animation is working
affich “sa.UserControl2.Temp” for every element.
When displaying if the end of the list, it want back to the begin of the list.
You have several issues here. I suggest you read up on DataTemplates and MVVM
First of all, the items you use to fill in the ListBox (or whatever other
ItemsControl-based element) should be Data Items, stricly. These cannot contain such thing asButtons. It’s much better to maintain Application Logic and UI separated in WPF.Here is an example of your ListBox with an ItemTemplate:
Data Item:
Also note that in order to support updates on the UI when you change these properties in the class
Temp, it will have to implement theSystem.ComponentModel.INotifyPropertyChangedinterface.Then, if you want to perform an action when the button is clicked for each item, you will have to use an
ICommand:XAML: