开发者

silverlight: how to display different views in listbox based on items object type?

Say, I've got two classes: AppleViewModel and OrangeViewModel. And I've got an ObservableCollection<object> of AppleViewModel's and OrangeViewModel's.

There are also two corresponding views: AppleView and OrangeView.

In app.xaml, there are DataTemplates for them:

<Application.Resources>
    <DataTemplate x:Key="AppleTemplate">
        <local:AppleView/>
    </DataTemplate>
    <DataTemplate x:Key="OrangeTemplate">
        <local:OrangeView/>
    </DataTemplate>
</Application.Resources>

And a converter just in case:

public class MyContentConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if(value is AppleViewModel)
            return Application.Current.Resources["AppleTemplate"] as DataTemplate;
        else if (value is OrangeViewModel)
            return Application.Current.Resources["OrangeTemplate"] as DataTemplate;
        else return null;
    }
}

It is referenced:

<phone:PhoneApplicationPage.Resources>
    <local:MyContentConverter x:Key="cConverter"/>
</phone:PhoneApplicationPage.Resources>

And this is the <ListBox/>:

    <ListBox ItemsSource="{Binding Fruits}" >
        <ListBox.ItemTemplate>
            <DataTemplate>
                <ContentControl ContentTemplate="{Binding Converter={StaticResource cConver开发者_StackOverflow社区ter}}"/>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

It shows just blank screen. How can I fix it so that the listbox would show different views for apples and oranges?


The DataContext for a ContentControl's ContentTemplate is actually the Content of the ContentControl and not its DataContext. So the problem may be that your Views is getting Null as DataContext.

Try it like this

<ListBox ItemsSource="{Binding Fruits}" >
    <ListBox.ItemTemplate>
        <DataTemplate>
            <ContentControl Content="{Binding}"
                            ContentTemplate="{Binding Converter={StaticResource cConverter}}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Update
Try to add some static info to your AppleView and OrangeView and see if it works

OrangeView

<StackPanel x:Name="LayoutRoot" Background="Orange" Orientation="Horizontal">
    <TextBlock Text="Orange View:"/>
    <TextBlock Text="{Binding Name}"/>
</StackPanel>

AppleView

<StackPanel x:Name="LayoutRoot" Background="Green" Orientation="Horizontal">
    <TextBlock Text="Apple View:"/>
    <TextBlock Text="{Binding Name}"/>
</StackPanel>

Also, I uploaded my sample app here so you can compare it to yours:
http://www.mediafire.com/?dqy47c69zgcmcnv

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜