![](/img/trans.png)
[英]How to make a list data with Observablecollection to show in listbox
[英]How to make a list of buttons dynamically and show them in the MainForm in a ListBox or ItemsControl
我是WPF的新手。 我想从一个类列表中说“按钮”,并在WPF的MainForm中有两个字段(ButtonContent,ButtonID)来制作按钮列表。 这背后的想法是,当MainForm将被加载时,我想使按钮动态列出。 链接http://www.codeproject.com/Articles/25030/Animating-Interactive-D-Elements-in-aD-Panel中已经给出了最佳示例,但是我只想使水平放置的按钮大小相等。
我如何在WPF中做到这一点? 先感谢您。
这就是我要做的方式。 这里有些方面需要您进一步研究,但这将使您入门。
首先,您需要ViewModel。 这是普通的旧对象。 它公开了与您的业务相关的属性和方法。 您提到了ButtonContent和ButtonID。 现在假设这两个都是字符串。 我假设您还需要一个按钮命令。
public class ButtonViewModel : INotifyPropertyChanged
{
private string _content;
public string Content
{
get{ return _content; }
set{ _content = value; OnPropertyChanged("Content"); }
}
// you'll need to implement INotifyPropertyChanged
// also take a look at RelayCommand
// here is your command for you're button
public ICommand ButtonCommand
{
get { return new RelayCommand(execute, canExecute); }
}
private void execute()
{
// my actual command code
}
private bool canExecute()
{
// this will automatically toggle the enabled state on my button
}
}
您将再有一个视图模型。 这将是您MainWindow的DataContext。
public class AppViewModel
{
public ObservableCollection<ButtonViewModel> MyButtons {get; set; }
public AppViewModel()
{
MyButtons = new ObservableCollection<ButtonViewModel>();
// add some demo data
MyButtons.Add(new ButtonViewModel() {ButtonContent = "Click Me!"});
}
}
现在,您需要实现视图。 在MainWindow xaml代码中。 添加您的xmlns:local名称空间。
<Window.DataContext>
<local:AppViewModel />
</Window.DataContext>
<ListBox ItemsSource="{Binding MyButtons}">
<ListBox.ItemsTemplate>
<DataTemplate>
<Button Command="{Binding ButtonCommand}" Content="{Binding Content}"/>
</DataTemplate>
<ListBox.ItemsTemplate>
</ListBox>
希望这可以帮助您朝正确的方向开始。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.