Reputation: 2092
I'm just playing with the grid class, to make it "cleaver". So I want to be able to use it in xaml and just specify how many rows I want, or columns etc, to do this I've got the code below. It all works fine, I used the loaded event to add rows and columns, but now I am thinking how should I unsubscribe from this event? I can't find straight forward information of how to do it?
public class MyFormGrid : Grid
{
public static readonly DependencyProperty ColumnsProperty =
DependencyProperty.Register("Columns", typeof(int), typeof(ASLFormGrid), new PropertyMetadata(0));
public static readonly DependencyProperty RowsProperty =
DependencyProperty.Register("Rows", typeof(int), typeof(ASLFormGrid), new PropertyMetadata(0));
public MyFormGrid()
{
Loaded += MyGrid_Loaded;
}
public int Columns
{
get { return (int)GetValue(ColumnsProperty); }
set { SetValue(ColumnsProperty, value); }
}
public int Rows
{
get { return (int)GetValue(RowsProperty); }
set { SetValue(RowsProperty, value); }
}
private void MyGrid_Loaded(object sender, RoutedEventArgs e)
{
for (var i = 0; i < Columns; i++)
{
ColumnDefinitions.Add(new ColumnDefinition());
}
for (var i = 0; i < Rows; i++)
{
RowDefinitions.Add(new RowDefinition(););
}
}
}
Kind Regards
Upvotes: 1
Views: 716
Reputation: 5944
This could easily be put inside your loaded event handler:
public class MyFormGrid : Grid
{
...
public MyFormGrid()
{
Loaded += MyGrid_Loaded;
}
...
private void MyGrid_Loaded(object sender, RoutedEventArgs e)
{
Loaded -= MyGrid_Loaded;
...
}
}
Upvotes: 2