我將一個項目控件綁定到數據源並使用網格作爲我的項目主機。我希望將這些物品放入網格中的正確單元格中(我可以這樣做),並且將它們堆疊起來,這樣它們就不會彼此重疊(我無法弄清楚如何將物品插入到堆疊面板或網格中的其他面板)。wpf使用網格作爲itemshost自動堆疊單個「單元格」中的多個項目
這裏是兩個階級的cs文件:
public class listofdata
{
public List<data> stuff { get; set; }
public listofdata()
{
stuff = new List<data>();
stuff.Add(new data(0, 0, "zeroa"));
stuff.Add(new data(0, 0, "zerob"));
stuff.Add(new data(1, 0, "onea"));
stuff.Add(new data(1, 0, "oneb"));
stuff.Add(new data(1, 1, "twoa"));
stuff.Add(new data(1, 1, "twob"));
}
}
public class data
{
public int x { set; get; }
public int y { set; get; }
public string text { get; set; }
public data(int x, int y, string text)
{
this.x = x;
this.y = y;
this.text = text;
}
}
}
這是我的XAML
<Window x:Class="GridTester.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:src="clr-namespace:GridTester"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
Title="MainWindow" >
<Window.Resources>
<DataTemplate DataType="{x:Type src:data}">
<Button Content="{Binding text}"/>
</DataTemplate>
<src:listofdata x:Key="MyDataSource"> </src:listofdata>
</Window.Resources>
<ListBox Name="Main" ItemsSource="{Binding Source={StaticResource MyDataSource},Path=stuff}">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<Grid Name="MyGrid">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
</Grid>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemContainerStyle>
<Style>
<Setter Property="Grid.Column" Value="{Binding x}"/>
<Setter Property="Grid.Row" Value="{Binding y}"/>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
</Window>
我的問題是,所有與結束按鈕「A」正在結束按鈕在b。 我不能看到如何使用XAML插入項目到動態創建的StackPanel
我試圖創建網格派生的類,想着攔截除了孩子們的加入stackpanels自己,然後將孩子從網格到堆疊面板,但試圖操縱項目主機中的子項會引發異常。
最終,我只是想讓我的數據源中的項目能夠綁定到網格中的「單元格」,並且如果多個項目綁定到同一個單元格,我希望它們堆疊。
你贏了」不能以目前的方式做到這一點。您需要在集合內部創建一個嵌套集合(爲此創建一個ViewModel),其中每個「x,y」項目都有一個子集合集,並且網格中的每個可視項目都有一個帶有「StackPanel」的ItemsControl並綁定到子集採集。 –