WPF控件初始化时未更新的属性
问题描述:
我是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(...);
// ...
}
}
}
答
你有这个绑定设置:
<UserControl ...>
<UniformGrid
Name="uniformGrid"
Rows="{Binding BoardRows}"
Columns="{Binding BoardColumns}"
>
</UniformGrid>
</UserControl>
的问题是,你的约束力不工作,因为绑定使用这是UserControl
的DataContext
默认的数据源。您可能没有设置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.Row
到BoardRows
财产的元素名为boardView
“,正是你想要的!
谢谢,修复了属性更新。我也必须将调用移动到InitializeGrid()以uniformGrid_Loaded;不能在构造函数中使用它。谢谢 :) – pkr298 2011-05-29 03:03:43