如何将内容控件附加到列表框?

时间:2012-08-27 20:34:03

标签: c# silverlight windows-phone-7 xaml

XAML:

<ListBox>
    <ListBox.ItemTemplate>
        <DataTemplate >  
            <StackPanel >
                <Grid  Width="335"  >
                    <TextBlock Text="{Binding Body}"  />
                </Grid>
            </StackPanel>
        </DataTemplate>
        <DataTemplate > 
            <StackPanel >
                <Grid  Width="335"  >
                    <Image  Source="{Binding Image}"  />
                </Grid>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

CS:

public class GardenConverter : ContentControl
{
    public DataTemplate TextTemplate { get; set; }
    public DataTemplate ImageTemplate { get; set; }

    protected override void OnContentChanged(object oldContent, object newContent)
    {
        base.OnContentChanged(oldContent, newContent);
        // apply the required template

        GardenObject garden = newContent as GardenObject;
        if (garden.image == "0")
        {
            ContentTemplate = TextTemplate;
        }
        else
        {
            ContentTemplate = ImageTemplate;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您可以尝试使用数据模板选择器。

public class GardenTemplateSelector : DataTemplateSelector
{
    public override DataTemplate SelectTemplate(object item, DependencyObject container)
    {
        var element = container as FrameworkElement;
        if (element != null && item != null && item is GardenObject)
        {   
            if((item as GardenObject).image == "0")
            {
                return element.FindResource("TextTemplate") as DataTemplate;            
            }
            else
            {
                return element.FindResource("ItemTemplate") as DataTemplate;            
            }           
        }

        return null;
    }
}

在XAML中,您需要定义TextTemplate和ItemTemplate。

有关详细信息,请参阅http://msdn.microsoft.com/en-us/library/system.windows.controls.datatemplateselector.aspx