views:

26

answers:

1

I have a list of items with the an interface like this

public interface INamedItem
{
    string DisplayName
    {
        get;
    }
}

In silverlight, I can bind to a listbox and show the display name, and that works.

However, depending on the value of DisplayName, I want to show it differently (use a different DataTemplate?).

If DisplayName has two '\t's it in, I want the the text before the first tab to be left justified, the text between the tabs centered, and the rest of the text right justified.

Is there any easy way to do this? I posted an "answer" below I found with google after adding this post, but I feel their has to be a better way.

A: 

So this seems to work (http://weblogs.asp.net/joewrobel/archive/2009/01/25/conditional-formatting-in-the-silverlight-datagrid.aspx) (ignore the fixed with columns).

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        INamedItem namedItem = value as INamedItem;
        if (namedItem == null)
        {
            TextBlock block = new TextBlock();
            block.Text = "";
            return block;
        }

        string[] tabSeperatedParts = namedItem.DisplayName.Split('\t');

        if (tabSeperatedParts.Count() != 3)
        {
            TextBlock block = new TextBlock();
            block.Text = namedItem.DisplayName;
            return block;
        }
        else
        {
            Grid grid = new Grid();
            grid.RowDefinitions.Add(new RowDefinition());
            for (int i = 0; i < 3; ++i)
            {
                ColumnDefinition col = new ColumnDefinition();
                col.MinWidth = 220;
                grid.ColumnDefinitions.Add(col);
                TextBlock text = new TextBlock();
                text.Text = tabSeperatedParts[i];
                grid.Children.Add(text);
                Grid.SetColumn(text, i);
            }
            ((TextBlock)grid.Children[0]).TextAlignment = TextAlignment.Left;
            ((TextBlock)grid.Children[1]).TextAlignment = TextAlignment.Center;
            ((TextBlock)grid.Children[2]).TextAlignment = TextAlignment.Right;
            return grid;
        }
    }

    <ScrollViewer.Resources>
        <magecrawlList:ListItemValueConverter x:Key="ItemConverter"/>
    </ScrollViewer.Resources>
    <ListBox ItemsSource="{Binding}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <ContentControl Content="{Binding Converter={StaticResource ItemConverter}}" HorizontalContentAlignment="Stretch" 
                                VerticalContentAlignment="Stretch" />
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
Donblas