嵌套控件的数据绑定

本文关键字:数据绑定 控件 嵌套 | 更新日期: 2023-09-27 18:20:56

我想在一些书中进行搜索,然后每本书的结果都显示在透视控件的单独项目中。每一个都由该数据透视项内的一个单独的LongListSelector控件表示。现在我想知道我应该为LongListSelector还是为它的父级(即Pivot)使用ItemsSource

有一本适用于所有书籍的词典:

private Dictionary<string, List<Model>> ItemResources = new Dictionary<string, List<Model>>();

以及用于每本书的List<Model>,其将被保存为上述ItemResources内的值。

这就是我所做的:

        foreach (var translation in ItemResources)
        {
            PivotItem pivotItem = new PivotItem
            {
                Header = translation.Key
            };
            LongListSelector lls = new LongListSelector
            {
                HideEmptyGroups = false,
                IsGroupingEnabled = false
            };
            lls.ItemTemplate = Resources["template"] as DataTemplate;
            lls.ItemsSource = translation.Value;
            pivotItem.Content = lls;
            ResultPivot.Items.Add(pivotItem);
        }

template是一个可重复使用的数据模板,我为ResultPivot:的每个pivotItem内的每个长列表选择器重新生成它

<phone:PhoneApplicationPage.Resources>
    <DataTemplate x:Key="template">
        <StackPanel Margin="0,0,0,0" Orientation="Vertical">
            <StackPanel Orientation="Horizontal" HorizontalAlignment="Left" Height="Auto" VerticalAlignment="Top" Width="455" Margin="3,20,3,0">
                <TextBlock Text="{Binding Name}" TextWrapping="Wrap" Style="{StaticResource PhoneTextLargeStyle}" FontSize="{StaticResource PhoneFontSizeNormal}"/>
                <TextBlock Text="{Binding Number}" TextWrapping="Wrap" Style="{StaticResource PhoneTextLargeStyle}" FontSize="{StaticResource PhoneFontSizeNormal}"/>
            </StackPanel>
            <StackPanel Height="Auto" VerticalAlignment="Top" HorizontalAlignment="Left" Width="455" Margin="3,0,3,20">
                <TextBlock Text="{Binding Text}" TextWrapping="Wrap" Style="{StaticResource PhoneTextLargeStyle}" FontSize="{StaticResource PhoneFontSizeNormal}"/>
            </StackPanel>
        </StackPanel>
    </DataTemplate>
</phone:PhoneApplicationPage.Resources>

问题是运行后屏幕上没有显示任何内容。我在调试中看到,值是存在的,但数据绑定似乎有问题。我该如何解决?感谢

(这是一个Windows Phone 8应用程序,但由于WPF及其广泛社区的概念相同,我也添加了它)

嵌套控件的数据绑定

UI目前无法知道源何时更改。当源更改时,您需要使用ObservableCollection或实现INotifyPropertyChanged接口来正确地通知UI。