我的viewmodel中有一个命令,执行时会将一个项添加到observablecollection
。在我看来,ItemsControl
的源绑定到此集合。因此,无论何时添加项目,每个项目都会显示combobox
和textblock
。
我要做的是,让每组组合框/文本块出现在最后一组的右边,直到它到达窗口的末尾,然后下一组将出现在第一组的下方,依此类推。计划将其放在ScrollViewer
中。到目前为止,我尝试过的所有内容都将每一组放在最后一组之下,而不是放在右边。
这是我的简单模型类:
public class DataModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private double _gridColumn;
public double GridColumn
{
get { return _gridColumn; }
set { _gridColumn = value; OnPropertyChanged("GridColumn"); }
}
// Create the OnPropertyChanged method to raise the event
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
以下是viewmodel的相关部分:
public class MainWindowViewModel : INotifyPropertyChanged
{
private int columnNum = 0;
private ObservableCollection<DataModel> _dataModelCollection = new ObservableCollection<DataModel>();
public ObservableCollection<DataModel> DataModelCollection
{
get { return _dataModelCollection; }
set { _dataModelCollection = value; OnPropertyChanged("DataModelCollection"); }
}
public void AddDataModel(object parameter)
{
DataModelCollection.Add(new DataModel {GridColumn = columnNum % 8 });
columnNum += 2;
}
}
现在我的观点是:
<Grid Background="#44D3D3D3">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="140*" />
<ColumnDefinition Width="7*" />
<ColumnDefinition Width="140*" />
<ColumnDefinition Width="7*" />
<ColumnDefinition Width="140*" />
<ColumnDefinition Width="7*" />
<ColumnDefinition Width="140*" />
<ColumnDefinition Width="7*" />
<ColumnDefinition Width="140*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="46*" />
<RowDefinition Height="139*" />
<RowDefinition Height="38*" />
<RowDefinition Height="78*" />
<RowDefinition Height="60*" />
<RowDefinition Height="50*" />
</Grid.RowDefinitions>
<Button Grid.Row="3"
Grid.Column="2"
Content="Add Set"
Command="{Binding AddDataModelCmd}"/>
<ItemsControl Grid.Row="4"
Grid.RowSpan="2"
Grid.ColumnSpan="9"
ItemsSource="{Binding DataModelCollection}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Grid.Column="{Binding GridColumn}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="140*" />
<ColumnDefinition Width="7*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="7" />
<RowDefinition Height="53" />
<RowDefinition Height="50" />
</Grid.RowDefinitions>
<ComboBox Grid.Column="0" Grid.Row="1" />
<TextBlock Text="tester"
Grid.Column="0"
Grid.Row="2"/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
我把ItemsPanelTemplate
设置为WrapPanel
,这让我得到了并排的结果,但我无法在每组项目之间找到任何间距。