2011-06-13 6 views
1

아래 코드는 각 시스템 글꼴 목록을 포함하는 세 개의 목록 상자 스택을 보여줍니다. 첫 번째는 정렬되지 않고 두 번째와 세 번째는 알파벳 순입니다. 그러나 세 번째 것은 비어 있습니다. 디버깅 할 때 VS 출력 창에 바인딩 오류 메시지가 표시되지 않습니다.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

당신은 당신이 InitalizeComponent를 호출하기 전에 SystemFonts를 초기화해야합니다. WPF 바인딩은 속성의 값이 변경된 것을 알 수있는 방법이 없습니다.

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

또는 더 나은 아직, 사용 : 바인딩은 DataContext를 사용하지 않기 때문에

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

, 나는 그가 그를 설정 할 때 중요한 믿지 않는다. 바인딩이 만들어지기 전에 SystemFonts를 설정해야합니다 (예 : InitializeComponent). – CodeNaked

+0

@ CodeNaked : 먼저 쓰기가 빠르다가 몇 번 편집합니다. :) 귀하의 의견을보기 전에 그것을 고정. –