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