我开始了解 XAML 数据绑定和使用 DataTemplate,它非常好。
采取下一步并将逻辑放入下面的代码中的最佳方法是什么,例如查看“Address2”中是否有任何内容,如果有则显示它,或者以不同的方式格式化外国地址等?
<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>
这是完整性背后的代码(Northwind 上自动生成的 LINQ to SQL 类):
CustomerDataContext dc = new CustomerDataContext();
var query = from companyName in dc.Customers
select companyName;
dataListBox.ItemsSource = query.ToList();