Domanda

Hey Guys I was just wandering if anyone can show me how to Programmatically change a ListBoxDataTemplate. So basically I have this 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>

Now when the user sets a certain setting on the Settings page, The ListBox DataTemplate must change to this:

<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>

Is it possble to do this? If so please someone help me. Thanks!

È stato utile?

Soluzione

One of many ways, define two DataTemplates in page Resources. Then you can set ListBox's ItemTemplate to any one of those two at run-time :

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

UPDATE :

Since, FindResource() function is not available in Windows Phone page, and as confirmed by OP this one works for him, so use following instead of above code :

MyListBox.ItemTemplate = (DataTemplate)this.Resources["DataTemplate2"]; 
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top