views:

133

answers:

2

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();
+1  A: 

You are looking for WPF Converters. Check out these converter samples for an overview of the kinds of things you can do. Essentially you can run any custom logic on an object before the value is set of a property by the binding. See: Binding Converter property.

You can also take a look at some of the work out of Codeplex of useful converters.

siz
A: 

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

<Window.Resources>
    <DataTemplate x:Key="CustomersTemplate">
        <Grid>
 ... snip ...
                <TextBlock Name="AddressLine" Text="{Binding Path=Address}"/>
 ... snip ...
        </Grid>
        <DataTemplate.Triggers>
           <DataTrigger Binding="{Binding Path=Address}" Value="">
              <Setter TargetName="AddressLine" Property="Visibility" Value="Collapsed"/>
           </DataTrigger>
        </DataTemplate.Triggers>
    </DataTemplate>
</Window.Resources>
Nir
perfect, that's it, thanks!
Edward Tanguay
How can this "format foreign addresses differently" ?
siz