2011-06-13 51 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