您好我有一个带有动态PivotItems的Pivot,我需要把带有StackPanels的LongListSelector和TextBlock放到PivotItem中。我在TextBlock中绑定文本时遇到问题。绑定PivotHeader工作正常,但我不知道如何将Name与TextBlock绑定。
XAML
<phone:Pivot x:Name="ShelfsPivot">
<phone:Pivot.HeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding Header}"/>
</DataTemplate>
</phone:Pivot.HeaderTemplate>
<phone:Pivot.ItemTemplate>
<DataTemplate>
<phone:LongListSelector ItemsSource="{Binding LongListSelector}">
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<StackPanel>
<CheckBox />
<TextBlock Text="{Binding Name}" />
</StackPanel>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
</DataTemplate>
</phone:Pivot.ItemTemplate>
</phone:Pivot>
和背后的代码
public class LongListData
{
public string Name { get; set; }
}
public class PivotData
{
public string Header { get; set; }
public LongListSelector LongListSelector { get; set; }
}
public partial class MainPage
{
public MainPage()
{
InitializeComponent();
var pivotDataList = new List<PivotData>();
var pivotItem1 = new PivotData {Header = "Header1", LongListSelector = new LongListSelector()};
var pivotItem2 = new PivotData {Header = "Header2", LongListSelector = new LongListSelector()};
pivotDataList.Add(pivotItem1);
pivotDataList.Add(pivotItem2);
ShelfsPivot.ItemsSource = pivotDataList;
var list = new List<LongListData>();
var item0 = new LongListData {Name = "Item1"};
var item1 = new LongListData {Name = "Item2"};
var item2 = new LongListData {Name = "Item3"};
list.Add(item0);
list.Add(item1);
list.Add(item2);
foreach (var pivotItem in ShelfsPivot.Items)
{
var longlist = pivotItem as PivotData;
if (longlist != null)
longlist.LongListSelector.ItemsSource = list;
}
}
}
答案 0 :(得分:1)
LongListSelector的项绑定本身不应该是LongListSelector,它应该是List或ObservableCollection。如果是静态数据,请使用List。如果是动态数据,请使用ObservableCollection。
所以,它看起来应该与此相似。
public class LongListData
{
public string Name { get; set; }
}
public class PivotData
{
public string Header { get; set; }
public ObservableCollection<LongListData> ListData { get; set; }
}
public MainPage()
{
InitializeComponent();
var list = new ObservableCollection<LongListData>();
var item0 = new LongListData {Name = "Item1"};
var item1 = new LongListData {Name = "Item2"};
var item2 = new LongListData {Name = "Item3"};
list.Add(item0);
list.Add(item1);
list.Add(item2);
var pivotDataList = new List<PivotData>();
var pivotItem1 = new PivotData {Header = "Header1", ListData = list};
var pivotItem2 = new PivotData {Header = "Header2", ListData = list};
pivotDataList.Add(pivotItem1);
pivotDataList.Add(pivotItem2);
ShelfsPivot.ItemsSource = pivotDataList;
}
你的绑定看起来像这样。
<phone:Pivot.ItemTemplate>
<DataTemplate>
<phone:LongListSelector ItemsSource="{Binding ListData}">
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<StackPanel>
<CheckBox />
<TextBlock Text="{Binding Name}" />
</StackPanel>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
</DataTemplate>
</phone:Pivot.ItemTemplate>
希望这有助于编码!