I’m new to WPF, and am having trouble getting the values for properties for a custom user control from the MainWindow XAML file.
Here, I want to get the value “8” as the number of rows and columns but in my InitializeGrid() method, the properties are never set. They are always “0”. What am I doing wrong?
Any references will also be appreciated.
This is my MainWindow.xaml (the relevant portions):
<local:BoardView
BoardRows="8"
BoardColumns="8"
/>
This is my BoardView.xaml:
<UniformGrid
Name="uniformGrid"
Rows="{Binding BoardRows}"
Columns="{Binding BoardColumns}"
>
</UniformGrid>
</UserControl>
And this is my 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( ... );
// ...
}
}
}
You have this binding set up:
The problem is that your binding is not working because the binding uses the default data source which is the
DataContextof theUserControl. You probably haven’t set theDataContextbut that’s OK because that’s not what you want anyway.You want to bind the number of
Rowsin theUniformGridto theBoardView.BoardRowsproperty. Since theUserControlis the previous code snippet is aBoardView, you can give theBoardViewa name and use theElementNamesyntax to refer to it like this:This says: “Bind
UniformGrid.Rowto theBoardRowsproperty of the element namedboardView“, just what you want!