我根据要求动态添加了8个按钮。
堆叠面板中的所有按钮。
int Total_images = img.Count;
int Page_size = 6;
int capacity = 0;
if (Total_images % Page_size == 0){
capacity = Total_images / Page_size;
}
else{
capacity = (Total_images / Page_size) + 1;
}
int j = 1;
if (sp.Children.Capacity==0){
//if (capacity <= 4){
for (int i = 0; i < capacity; ++i){
Button button = new Button(){
Content = string.Format("" + j),
Tag = i
};
j += 1;
button.Width = 20;
button.Height = 20;
button.Click += new RoutedEventHandler(button_Click);
sp.Children.Add(button);
}
}
有没有办法做到这一点?
答案 0 :(得分:1)
理想情况下,您应该使用视图模型进行集合绑定 这看起来像这样,请注意,这只是指向正确方向的基本示例
class ViewModelPager : INotifyPropertyChanged
{
public ObservableCollection<int> Items { get; } = new ObservableCollection<int>(Enumerable.Range(1, 20));
public IEnumerable<int> ShowItems => Items.Skip(Page * 4).Take(4);
private int page;
public event PropertyChangedEventHandler PropertyChanged;
public int Page
{
get { return page; }
set
{
page = value;
PropertyChanged.Invoke(this, new PropertyChangedEventArgs(nameof(Page)));
PropertyChanged.Invoke(this, new PropertyChangedEventArgs(nameof(ShowItems)));
}
}
public ICommand Next { get; set; }
public ICommand Previous { get; set; }
}
然后在你的XAML中你将没有代码
<Window x:Class="WpfApp1.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:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.DataContext>
<local:ViewModelPager/>
</Window.DataContext>
<StackPanel >
<ItemsControl ItemsSource="{Binding ShowItems}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="{Binding}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<Slider Value="{Binding Page}"/>
<Button Command="{Binding Next}">Next</Button>
<Button Command="{Binding Previous}">Previous</Button>
</StackPanel>
</Window>
有关如何实现命令的信息,请参阅RelayCommand
答案 1 :(得分:0)
清除StackPanel并添加新按钮:
NextButton_Click(sender...)
{
sp.Children.Clear();
for(i = 0; i < 3; i++)
{
Button button = new Button(){
Content = (i+5).ToString();
};
button.Width = 20;
button.Height = 20;
button.Click += new RoutedEventHandler(button_Click);
sp.Children.Add(button);
}
}
PreviousButton_Click(sender...)
{
sp.Children.Clear();
for(i = 0; i < 3; i++)
{
Button button = new Button(){
Content = (i+1).ToString();
};
button.Width = 20;
button.Height = 20;
button.Click += new RoutedEventHandler(button_Click);
sp.Children.Add(button);
}
}