替换DataTemplate中的元素

时间:2014-08-08 18:31:24

标签: windows-phone-8 datatemplate datatemplateselector

我有一个带有ItemTemplate的LongListSelector,如下所示:

<LongListSelector.ItemTemplate>
    <DataTemplate>
       <StackPanel>

          Here I have a lot of elements that are always the same.
          .
          .
          .
          and one that varies

       </StackPanel>
    </DataTemplate>     
</LongListSelector.ItemTemplate>

我知道如何根据项目类型使用此TemplateSelector类来更改ItemTemplate中的所有内容。

我的问题是,如何使用模板选择器只更改一个不同的项目,所以我不需要重复其他所有元素。

我尝试在ContentControl内使用ContentPresenterStackPanel但没有成功

1 个答案:

答案 0 :(得分:-1)

您希望在XAML中创建数据触发器,以检查每个项目是否是您正在寻找的项目。

This SO question足以让您走上正轨。它最终会看起来像这样:

<Style TargetType="TabItem">
        <Style.Triggers>
            <!-- Styling for elements that are NOT the last item -->
            <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Converter={StaticResource LastItemConverter}}" Value="False">
                <Setter Property="Template">
                    <Setter.Value>
                        .
                        .
                        .
                    </Setter.Value>
                </Setter>
             </DataTrigger>
            <!-- Styling for elements that are the last item -->
            <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Converter={StaticResource LastItemConverter}}" Value="True">
                <Setter Property="Template">
                    <Setter.Value>
                        .
                        .
                        .
                    </Setter.Value>
                </Setter>
             </DataTrigger>

转换器看起来像这样 - 取决于你绑定的UI元素。

public class IsLastItemInContainerConverter : IValueConverter
{
    public object Convert(object value, Type targetType,
                          object parameter, CultureInfo culture)
    {
        DependencyObject item = (DependencyObject)value;
        TabControl tc = (TabControl)TabControl.ItemsControlFromItemContainer(item);


        // Return true for the first and last element 
        // (so they are similarly styled compared to other elements).
        if (tc.ItemContainerGenerator.IndexFromContainer(item) == tc.Items.Count - 1) {
            return true;
        }
        else if (tc.ItemContainerGenerator.IndexFromContainer(item) == 0)
        {
            return true;
        }
        else
        {
            return false;
        }

    }

希望有所帮助。