Reputation: 1761
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( ... );
// ...
}
}
}
Upvotes: 3
Views: 1646
Reputation: 34240
You have this binding set up:
<UserControl ...>
<UniformGrid
Name="uniformGrid"
Rows="{Binding BoardRows}"
Columns="{Binding BoardColumns}"
>
</UniformGrid>
</UserControl>
The problem is that your binding is not working because the binding uses the default data source which is the DataContext
of the UserControl
. You probably haven't set the DataContext
but that's OK because that's not what you want anyway.
You want to bind the number of Rows
in the UniformGrid
to the BoardView.BoardRows
property. Since the UserControl
is the previous code snippet is a BoardView
, you can give the BoardView
a name and use the ElementName
syntax to refer to it like this:
<UserControl Name="boardView" ...>
<UniformGrid
Name="uniformGrid"
Rows="{Binding BoardRows, ElementName=boardView}"
Columns="{Binding BoardColumns, ElementName=boardView}"
>
</UniformGrid>
</UserControl>
This says: "Bind UniformGrid.Row
to the BoardRows
property of the element named boardView
", just what you want!
Upvotes: 1