C# 如何从列表框中分割按钮控件

C# 如何从列表框中分割按钮控件,c#,wpf,button,data-binding,listbox,C#,Wpf,Button,Data Binding,Listbox,我在WPF表单中有一个ListBox控件,其中包含按钮控件 按钮控件的int值类似于65 我想显示7个按钮,共65个 我还想把内容放在按钮上,上面写着1-10、11-20、21-30等等。和65值来自数据库。您可以使用ListBox.ItemTemplate创建包含按钮的列表框。 以下是我创建的示例,它将ObservalbleCollection绑定为listbox的ItemSource: <ListBox ItemsSource="{Binding ListDiv}">

我在WPF表单中有一个ListBox控件,其中包含按钮控件

按钮控件的int值类似于65

我想显示7个按钮,共65个


我还想把内容放在按钮上,上面写着
1-10、11-20、21-30等等。
和65值来自数据库。

您可以使用ListBox.ItemTemplate创建包含按钮的列表框。 以下是我创建的示例,它将ObservalbleCollection绑定为listbox的ItemSource:

<ListBox ItemsSource="{Binding ListDiv}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <Button Content="{Binding}"/>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
</ListBox>

相同的.cs文件为:

public partial class MainWindow : Window, INotifyPropertyChanged
{
    private ObservableCollection<string> listDiv;
    public ObservableCollection<string> ListDiv
    {
        get { return listDiv; }
        set
        {
            listDiv = value;
            OnNotifyPropertyChanged("ListDiv");
        }
    }

    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = this;
        GetList();
    }

    private void GetList()
    {
        ListDiv = new ObservableCollection<string>();
        ListDiv.Add("1-10");
        ListDiv.Add("2-20"); 
        ListDiv.Add("3-30"); 
        ListDiv.Add("4-40");
        ListDiv.Add("5-50");
        ListDiv.Add("6-60");
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnNotifyPropertyChanged(string S)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(S));
    }
}
public分部类主窗口:窗口,INotifyPropertyChanged
{
私有可观测收集列表div;
公共可观测收集列表div
{
获取{return listDiv;}
设置
{
listDiv=值;
OnNotifyPropertyChanged(“ListDiv”);
}
}
公共主窗口()
{
初始化组件();
this.DataContext=this;
GetList();
}
私有void GetList()
{
ListDiv=新的ObservableCollection();
列表div.添加(“1-10”);
列表div.添加(“2-20”);
列表div.添加(“3-30”);
列表div.添加(“4-40”);
列表div.添加(“5-50”);
列表div.添加(“6-60”);
}
公共事件属性更改事件处理程序属性更改;
私有void OnNotifyPropertyChanged(字符串S)
{
if(PropertyChanged!=null)
PropertyChanged(即新PropertyChangedEventArgs);
}
}
您可以使用自己的逻辑部分在GetList()方法中获取可观察的集合

别忘了设置类的DataContext。


希望这会对您有所帮助,谢谢。

除了这个想法之外,您还有什么想法?仍然不清楚,请尝试用图像进行解释。谢谢您的评论,但我使用的是MVVM体系结构。。我忘了问这个问题了。。