I am trying to bind name with comma-separated values. In the last item I don't want to add a comma. Can you please let me know how to remove the last comma in WinRT application?
<ItemsControl ItemsSource="{Binding xxxx}" >
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"></StackPanel>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Margin="0,-6,0,0" >
<HyperlinkButton x:Name="name" Content="{Binding Name}" VerticalAlignment="Top" Style="{ThemeResource TileContentHyperlinkStyle}" ></HyperlinkButton>
<TextBlock x:Name="Comma" x:Uid="/Resources/Comma" Style="{ThemeResource TileContentStyle}" VerticalAlignment="Center" Margin="0,0,5,0" />
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
Example output:
Ramesh ,Sutha,Nikhil,
<=== (need to remove last comma)
You can add a flag in your view model to detect whether to show the comma. For example:
In
MyViewModel
, add aIsLast
property as the flag:Then in XAML, bind the
Visibility
property ofTextBlock
toIsLast
:Here we need a
Converter
to convertbool
toVisibility
:After this, we can add some data to have a test:
Update:
Adding a flag for comma in the viewmodel is not a good approach. Using a data template selector to switch between a template with and without the comma may be a better way.
To do this, we need two templates first, the template for the first item should have no comma and the others need a comma:
Then we need to create a data template selector class which inherits from
DataTemplateSelector
class and override theSelectTemplateCore
method to implement the logic. In the method, we can useItemsControl.ItemsControlFromItemContainer
method to get theItemsControl
andItemsControl.IndexFromContainer
method to get the index of the container then detect whether the item is the first item of theItemsControl
by comparing the index:After this we can add
MyTemplateSelector
inPage.Resources
like following:Then we can use it in
ItemsControl
: