I'm learning WPF and try to create a fully skinnable and configurable backgammon board. The board contains a numbers of pins which are derived from a grid and contain a number of ellipses (the checkers). The pins are placed on another grid 'MainGrid' which is basically the board. The parameters for creating the pins are stored in a resource directory as a string. The string is actually an attached property of the board. (the configuration example only shows the configuration for the two bar pins)
<Style x:Key="MainGrid_style" TargetType="Grid">
// ...
<Setter Property="bgb:BgBoard.BarParams" Value="Bottom,5,8,1,1,4/Top,5,8,6,1,4"/>
</Style>
The style is applied to the main grid as follows :
<Grid x:Name="MainGrid" Style="{DynamicResource MainGrid_style}">
My board is coded as follows :
public partial class BgBoard : Window
{
public static DependencyProperty BarParamsProperty = DependencyProperty.RegisterAttached("BarParams", typeof(string),
typeof(BgBoard), new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.None,
new PropertyChangedCallback(BarParamsPropertyChanged)));
public static string GetBarParams(Grid Grid) { return Convert.ToString(Grid.GetValue(BarParamsProperty)); }
public static void SetBarParams(Grid Grid, string Value) { Grid.SetValue(BarParamsProperty, Value); }
private static void BarParamsPropertyChanged(Object Sender, DependencyPropertyChangedEventArgs e)
{
Grid Grid = (Grid)Sender;
string[] sBarParams = GetBarParams(Grid).Split('/');
for (int player = 0; player <= 1; player++)
{
// *** sBarParams[player] is further parsed and parameters are determined
BgPin pin = new BgPin(type, size);
// *** Set the other pin params
pin.Name = "Bar" + player;
Grid.Children.Add(pin);
}
}
This works perfectly and puts the two bar pins on the board as expected. However, now i want to be able to reference the two pins as an array ( _Bar[0] and _Bar[1] )
So i added the following field to my board :
private BgPin[] _Bar = new BgPin[2];
I cannot instantiate or assign these pins via the attached property because the BarParamsPropertyChanged method is static.
So in my Board's constructor i've added :
public BgBoard()
{
InitializeComponent();
_Bar[0] = (BgPin)MainGrid.FindName("Bar0");
}
However, this doesn't work as _Bar[0] is still null after this instruction. Any ideas how i could reference the object with name "Bar0" as _Bar[0]? Any solution is ok. It is not required to work via the 'name'-property.