2011-06-13 60 views
1

下面的代碼應該顯示三個列表框的堆棧,每個列表框包含所有系統字體的列表。第一個是未排序的,第二個和第三個是按字母順序排列的。但第三個是空的。調試時,在VS Output窗口中看不到任何綁定錯誤消息。WPF綁定語法問題

標記是:

<Window x:Class="FontList.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:local="clr-namespace:FontList" 
    Title="MainWindow" Height="600" Width="400"> 
<Grid> 
    <Grid.RowDefinitions> 
     <RowDefinition Height="*"></RowDefinition> 
     <RowDefinition Height="*"></RowDefinition> 
     <RowDefinition Height="*"></RowDefinition> 
    </Grid.RowDefinitions> 
    <ListBox Grid.Row="0" ItemsSource="{Binding Source={x:Static Fonts.SystemFontFamilies}}" /> 
    <ListBox Grid.Row="1" ItemsSource="{Binding Path=SystemFonts}" /> 
    <ListBox Grid.Row="2" ItemsSource="{Binding Source={x:Static local:MainWindow.SystemFonts}}" /> 
</Grid> 

後面的代碼是:

using System.Collections.Generic; 
using System.Linq; 
using System.Windows; 
using System.Windows.Media; 

namespace FontList 
{ 
    public partial class MainWindow : Window 
    { 
     public static List<FontFamily> SystemFonts { get; set; } 

     public MainWindow() { 
      InitializeComponent(); 
      DataContext = this; 
      SystemFonts = Fonts.SystemFontFamilies.OrderBy(f => f.ToString()).ToList(); 
     } 
    } 
} 

有什麼不對第三結合?

回答

2

需要初始化SystemFonts你打電話之前InitalizeComponent。 WPF綁定無法知道屬性的值發生了變化。

public MainWindow() { 
    SystemFonts = Fonts.SystemFontFamilies.OrderBy(f => f.ToString()).ToList(); 
    InitializeComponent(); 
    DataContext = this; 
} 

或更好,但使用:

static MainWindow() { 
    SystemFonts = Fonts.SystemFontFamilies.OrderBy(f => f.ToString()).ToList(); 
} 

public MainWindow() { 
    InitializeComponent(); 
    DataContext = this; 
} 
1

綁定在InitializeComponent期間創建,而SystemFontsnull。設置後,綁定無法知道該屬性的值已更改。

您也可以在一個靜態構造函數中設置SystemFonts,這可能是較好的,因爲它是一個靜態屬性。否則,每個MainWindow的實例化都將更改靜態屬性。

public partial class MainWindow : Window { 
    public static List<FontFamily> SystemFonts{get; set;} 

    static MainWindow { 
     SystemFonts = Fonts.SystemFontFamilies.OrderBy(f => f.ToString()).ToList(); 
    } 

    ... 
} 
+0

由於綁定不使用DataContext的,我不相信,他將它的問題。系統字體需要在綁定創建之前設置(即InitializeComponent)。 – CodeNaked 2011-06-13 23:44:54

+0

@CodeNaked:我先寫快,然後編輯幾次。 :)修復它之前看到您的評論。 – 2011-06-13 23:49:38