I’m starting to understand XAML data binding and using the DataTemplate and it’s pretty nice.
What is the best way to take the next step and put logic into the code below, e.g. look to see if there is anything in ‘Address2’ and if so display it, or format foreign addresses differently, etc.?
<Window.Resources> <DataTemplate x:Key='CustomersTemplate'> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width='35'/> <ColumnDefinition Width='*'/> </Grid.ColumnDefinitions> <Rectangle Height='30' Width='30' Margin='0 4 0 0' Fill='LightGreen' Grid.Column='0' VerticalAlignment='Top'/> <StackPanel Margin='3 0 0 10' Orientation='Vertical' Grid.Column='1'> <TextBlock Text='{Binding Path=ContactName}'/> <TextBlock Text='{Binding Path=CompanyName}'/> <TextBlock Text='{Binding Path=Address}'/> <TextBlock> <TextBlock.Text> <MultiBinding StringFormat='{}{0}, {1} {2}'> <Binding Path='City'/> <Binding Path='Region'/> <Binding Path='PostalCode'/> </MultiBinding> </TextBlock.Text> </TextBlock> </StackPanel> </Grid> </DataTemplate> </Window.Resources> <Grid> <ListBox Name='dataListBox' ItemTemplate='{StaticResource CustomersTemplate}'/> </Grid>
Here is the code behind for completeness (autogenerated LINQ to SQL classes on Northwind):
CustomerDataContext dc = new CustomerDataContext(); var query = from companyName in dc.Customers select companyName; dataListBox.ItemsSource = query.ToList();
Welcome to the wonderful world of triggers, here is the code to remove blank address lines from your example:
I’ve added a name to the address text block and added a DataTrigger to hide it when the address is blank