WPF——TargetNullValue(如何在綁定空值顯示默認字符)


說明:在數據綁定時,如果有些字段為空值,那么在數據綁定時可以用默認值來顯示為空的字段。

 

 1  <Grid>
2 <ListBox x:Name="lstPeople" Width="400">
3 <ListBox.ItemTemplate>
4 <DataTemplate>
5 <StackPanel Orientation="Horizontal">
6 <TextBlock Text="{Binding Path=FirstName}" />
7 <TextBlock Text=" " />
8 <TextBlock Text="{Binding LastName}" />
9 <TextBlock Text=", " />
10 <TextBlock Text="{Binding Age, TargetNullValue='Age Unknown'}" />
11 </StackPanel>
12 </DataTemplate>
13 </ListBox.ItemTemplate>
14 </ListBox>
15 </Grid>

 

 1  public partial class MainWindow : Window
2 {
3 List<Person> lst;
4
5 public MainWindow()
6 {
7 InitializeComponent();
8 lst = new List<Person>();
9 lst.Add(new Person() {FirstName="John", LastName="Doe", Age=34});
10 lst.Add(new Person() { FirstName = "Jane", LastName = "Doe" });
11 lst.Add(new Person() { FirstName = "Jack", LastName = "Frost", Age = 300 });
12 }
13
14 private void Window_Loaded(object sender, RoutedEventArgs e)
15 {
16 lstPeople.ItemsSource = lst;
17 }
18 }
19
20 public class Person
21 {
22 public string FirstName { get; set; }
23 public string LastName { get; set; }
24 public int? Age { get; set; }
25 }

 




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM