I have a simple Observable collection with two public properties, int ID and List Targets. The code-behind looks like (simplified code to remove unnecessary and not relevant code):
public class MyClass
{
public ObservableCollection<SomeClass> jobs;
public class SomeClass
{
private int id;
private List<string> targets;
public int ID
{
get { return id; }
set { id = value; }
}
public List<string> Targets
{
get { return targets; }
set { targets = value; }
}
public SomeClass(int _id, List<string> _targets)
{
id = _id;
targets = _targets;
}
}
public MyClass()
{
InitializeComponent();
jobs = new ObservableCollection<SomeClass>();
myListView.ItemsSource = jobs; //jobs is populated from a a loader in Window_Loaded
}
}
The ListView and binding in the xaml look like:
<ListView Name="MyListView" ItemsSource="{Binding Path=jobs, RelativeSource={RelativeSource AncestorType=Window},
Mode=OneWay}" Width="480" Height="155" HorizontalAlignment="Right" VerticalAlignment="Top" Margin="0,35,10,0" >
<ListView.ContextMenu>
<ContextMenu Name="contextMenuJobRemove">
<ContextMenu.BitmapEffect>
<OuterGlowBitmapEffect />
</ContextMenu.BitmapEffect>
<MenuItem Header="Remove" Click="contextMenuJobRemove_Click" CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=Parent}"/>
</ContextMenu>
</ListView.ContextMenu>
<ListView.View>
<GridView AllowsColumnReorder="True" ColumnHeaderToolTip="Broadcast call targets">
<GridViewColumn DisplayMemberBinding="{Binding Path=ID}" Header="ID" Width="50" />
<GridViewColumn DisplayMemberBinding="{Binding Path=Targets}" Header="Targets" Width="100" />
</GridView>
</ListView.View>
</ListView>
So when the ListView displays, the Targets columns rightfully displays “(Collection)”. Ideally I’d like this column to display something like String.Join(",", Targets.ToArray()). How can this be done, and am I doing this in the xaml or code-behind?
One method would be a converter in the binding.
However this will only update once the property is changed (not the collection contents). So it might be better to expose a display string property in your object and fire change notifications for that property whenever the list changes. If the collection does not change in the first place those notifications are obviously not necessary.