2011-05-29 37 views
3

我是WPF的新手,並且無法從MainWindow XAML文件獲取自定義用戶控件的屬性值。WPF控件初始化時未更新的屬性

在這裏,我想獲取值「8」作爲行數和列數,但在我的InitializeGrid()方法中,屬性從不設置。他們總是「0」。我究竟做錯了什麼?

任何參考也將不勝感激。


這是我MainWindow.xaml(相關部分):

<local:BoardView 
    BoardRows="8" 
    BoardColumns="8" 
    /> 

這是我BoardView.xaml:

<UniformGrid 
     Name="uniformGrid" 
     Rows="{Binding BoardRows}" 
     Columns="{Binding BoardColumns}" 
     > 

    </UniformGrid> 
</UserControl> 

這是我BoardView.xaml.cs:

[Description("The number of rows for the board."), 
Category("Common Properties")] 
public int BoardRows 
{ 
    get { return (int)base.GetValue(BoardRowsProperty); } 
    set { base.SetValue(BoardRowsProperty, value); } 
} 
public static readonly DependencyProperty BoardRowsProperty = 
    DependencyProperty.Register("BoardRows", typeof(int), typeof(UniformGrid)); 

[Description("The number of columns for the board."), 
Category("Common Properties")] 
public int BoardColumns 
{ 
    get { return (int)base.GetValue(BoardColumnsProperty); } 
    set { base.SetValue(BoardColumnsProperty, value); } 
} 
public static readonly DependencyProperty BoardColumnsProperty = 
    DependencyProperty.Register("BoardColumns", typeof(int), typeof(UniformGrid)); 

public BoardView() 
{ 
    InitializeComponent(); 
    DataContext = this; 
    InitializeGrid(); 
} 

private void InitializeGrid() 
{ 
    int rows = BoardRows; 
    int cols = BoardColumns; 

    for (int i = 0; i < rows; i++) 
    { 
     for (int j = 0; j < cols; j++) 
     { 
      uniformGrid.Children.Add(...); 
      // ... 
     } 
    } 
} 

回答

1

你有這個綁定設置:

<UserControl ...> 
    <UniformGrid 
     Name="uniformGrid" 
     Rows="{Binding BoardRows}" 
     Columns="{Binding BoardColumns}" 
     > 

    </UniformGrid> 
</UserControl> 

的問題是,你的約束力不工作,因爲綁定使用這是UserControlDataContext默認的數據源。您可能沒有設置DataContext,但這沒關係,因爲這不是您想要的。

您想要將UniformGrid中的的數量綁定到BoardView.BoardRows屬性。由於UserControl是前面的代碼片段一個BoardView,你可以給BoardView一個名稱,並使用ElementName語法來指代這樣的:

<UserControl Name="boardView" ...> 
    <UniformGrid 
     Name="uniformGrid" 
     Rows="{Binding BoardRows, ElementName=boardView}" 
     Columns="{Binding BoardColumns, ElementName=boardView}" 
     > 

    </UniformGrid> 
</UserControl> 

這是說:「綁定UniformGrid.RowBoardRows財產的元素名爲boardView「,正是你想要的!

+0

謝謝,修復了屬性更新。我也必須將調用移動到InitializeGrid()以uniformGrid_Loaded;不能在構造函數中使用它。謝謝 :) – pkr298 2011-05-29 03:03:43