我试图创建一个矩阵,它应该显示如下按钮:
[按钮] [按钮]
[按钮] [按钮]
所以这将是一个2x2矩阵。但我也想动态创建一个更大的矩阵(如5x5或10x10)。
我已经考虑过不同的想法,例如使用StackPanels或网格(我不知道如何从我的ViewModel访问行/列并将按钮添加到特定的行/列)。 / p>
目前我已经考虑过使用2 ObservableCollection
的想法,就像ListBox中的ListBox一样,并将Orientation设置为Horizontal,但这是一个糟糕的解决方案。这就是我目前所拥有的:
XAML:
<ListBox x:Name="ContentPanel" Grid.Row="1" ItemsSource="{Binding ButtonList}">
<ItemsControl >
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</ListBox>
视图模型:
public class MainViewModel : ViewModelBase
{
/// <summary>
/// Initializes a new instance of the MainViewModel class.
/// </summary>
public MainViewModel()
{
_buttonlist = new ObservableCollection<ObservableCollection<Button>>();
for (int j = 0; j < 5; j++)
{
_mylist = new ObservableCollection<Button>();
for (int i = 0; i < 5; i++) //Add Button to my list of Buttons
{
Button b = new Button();
b.Height = 100;
b.Width = 100;
b.Background = new SolidColorBrush(Colors.Red);
b.Content = "Hallo";
_mylist.Add(b);
}
_buttonlist.Add(_mylist); //Add a ListBox-Item to ButtonList, which has 5 Buttons in it
}
}
private ObservableCollection<ObservableCollection<Button>> _buttonlist { get; set; } //List with Buttons
public ObservableCollection<ObservableCollection<Button>> ButtonList
{
get
{
return _buttonlist;
}
set
{
_buttonlist = value;
RaisePropertyChanged(() => ButtonList);
}
}
private ObservableCollection<Button> _mylist { get; set; } //List with ListBox, so my rows
public ObservableCollection<Button> MyList
{
get
{
return _mylist;
}
set
{
_mylist = value;
RaisePropertyChanged(() => MyList);
}
}
}
它也没有显示按钮,因为我不知道要设置什么DisplayMemberPath ..它只显示System.Collections.ObjectModel.ObservableCollection
....