以编程方式更改ListBox DataTemplate

时间:2014-03-10 03:16:35

标签: c# xaml windows-phone-8 listbox datatemplate

Hey Guys如果有人能告诉我如何以编程方式更改ListBoxDataTemplate,我只是在徘徊。基本上我有这个DataTemplate:

<DataTemplate x:Key="DataTemplate1">
        <Grid toolkit:TiltEffect.IsTiltEnabled="True" d:DesignWidth="446" Width="446" d:DesignHeight="108" Height="108">
            <TextBlock TextWrapping="NoWrap" Text="{Binding AccountTitle}" VerticalAlignment="Top" Width="456" HorizontalAlignment="Left" Height="40" FontFamily="Segoe WP" FontSize="28" />
            <TextBlock TextWrapping="NoWrap" Text="{Binding AccountUsername}" VerticalAlignment="Top" Width="456" Margin="0,33,0,0" HorizontalAlignment="Left" Height="35" FontFamily="Segoe WP" FontSize="24" />
            <TextBlock TextWrapping="NoWrap" Text="{Binding AccountWebsite}" VerticalAlignment="Top" Width="456" Margin="0,61,0,0" HorizontalAlignment="Left" Height="35" FontFamily="Segoe WP" FontSize="24" />
            <TextBlock TextWrapping="NoWrap" Text="{Binding FolderID}" VerticalAlignment="Top" Width="456" Margin="0,96,0,-13" HorizontalAlignment="Left" Height="35" FontFamily="Segoe WP" FontSize="24" Opacity="0" Visibility="Collapsed" />
            <TextBlock TextWrapping="NoWrap" Text="{Binding AccountDate}" VerticalAlignment="Top" Margin="0,38,0,0" FontFamily="Segoe WP" FontSize="20" TextAlignment="Right" HorizontalAlignment="Right" />
        </Grid>
</DataTemplate>

现在,当用户在“设置”页面上设置某个设置时,ListBox DataTemplate必须更改为:

<DataTemplate x:Key="DataTemplate1">
        <Grid toolkit:TiltEffect.IsTiltEnabled="True" d:DesignWidth="446" Width="446" d:DesignHeight="108" Height="108">
            <TextBlock TextWrapping="NoWrap" Text="{Binding AccountTitle}" VerticalAlignment="Top" Width="456" HorizontalAlignment="Left" Height="40" FontFamily="Segoe WP" FontSize="28" />
            <TextBlock TextWrapping="NoWrap" Text="{Binding AccountDate}" VerticalAlignment="Top" Margin="0,38,0,0" FontFamily="Segoe WP" FontSize="20" TextAlignment="Right" HorizontalAlignment="Right" />
        </Grid>
</DataTemplate>

是否有可能这样做?如果是这样,请有人帮助我。 谢谢!

1 个答案:

答案 0 :(得分:6)

在众多方法中,有一种方法是在页面资源中定义两个DataTemplate。然后,您可以在运行时将ListBox的ItemTemplate设置为这两个中的任何一个:

MyListBox.ItemTemplate = (DataTemplate)FindResource("DataTemplate2"); 

更新:

由于FindResource()功能在Windows Phone页面中不可用,并且由OP确认这个功能对他有效,因此请使用以下代码而不是上述代码:

MyListBox.ItemTemplate = (DataTemplate)this.Resources["DataTemplate2"];