Properties not updated during WPF management initialization

I am new to WPF and it is difficult for me to get the property values ​​for the 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 will never be set. They are always "0". What am I doing wrong?

Any links would also be appreciated.


This is my MainWindow.xaml (relevant parts):

<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( ... );
            // ...
        }
    }
}
+3
source share
1 answer

You have this binding set:

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

    </UniformGrid>
</UserControl>

, , , DataContext UserControl. , DataContext, , , .

Rows UniformGrid BoardView.BoardRows. UserControl - - a 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", , !

+1

All Articles