如何恢复DataTemplate?

时间:2014-02-22 10:16:42

标签: c# xaml windows-phone-8

我为LongListSelector设置了一个DataTemplate:

<ctl:LongListSelector Loaded="listbox_Loaded" Name="listbox" SelectionChanged="listbox_selectionChanged">
    <ctl:LongListSelector.ItemTemplate>
        <DataTemplate>
            <Border Background="Gray" MouseLeftButtonDown="listbox_itemClicked">
                <TextBlock Text="{Binding}"  TextWrapping="Wrap" Width="350"/>
            </Border>
        </DataTemplate>
    </ctl:LongListSelector.ItemTemplate>
</ctl:LongListSelector>

经过一些操作后,我从代码中更改了一些项目的视图,现在需要恢复此DataTemplate,如上所述。如何从代码中执行此操作?

有一些处理程序。第一个从TextBlock获取值,第二个将所选项目变为红色。当我选择另一个项目时,我应该将之前的颜色返回到灰色。似乎尝试恢复DataTemplate不起作用。

    private void listbox_selectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var lb = (LongListSelector)sender;
        var lbi = lb.SelectedItem.ToString();
        lb.ItemTemplate = Resources["ItemTemplateLongListSelector"] as DataTemplate;
        var categoryCode = CategoryCodes.ElementAt(CategoryNames.IndexOf(lbi));
        addedItem.Category = categoryCode;
    }

    private void listbox_itemClicked(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
        var border = (Border)sender;
        var borderBrush = new SolidColorBrush();
        borderBrush.Color = Color.FromArgb(255, 255, 0, 0);
        border.Background = borderBrush;
    }

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以制作资源

<phone:PhoneApplicationPage.Resources>

    <DataTemplate x:Key="ItemTemplateLongListSelector">
        <Border Background="Gray"
                MouseLeftButtonDown="listbox_itemClicked">
            <TextBlock Text="{Binding}"
                       TextWrapping="Wrap"
                       Width="350" />
        </Border>
    </DataTemplate>

</phone:PhoneApplicationPage.Resources>

DataTemplate 绑定到 ItemTemplate

        <phone:LongListSelector Loaded="listbox_Loaded"
                                Name="LongListSelector"
                                SelectionChanged="listbox_selectionChanged"
                                ItemTemplate="{StaticResource ItemTemplateLongListSelector}" />

要在代码中设置标准DataTemplate,您可以执行以下操作:

LongListSelector.ItemTemplate = Application.Current.Resources["ItemTemplateLongListSelector"] as DataTemplate;

OR

LongListSelector.ItemTemplate = Resources["ItemTemplateLongListSelector"] as DataTemplate;

我希望这会有所帮助!