Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing XAML objects in C# View Model

Tags:

c#

wpf

xaml

i have set up a Grid in my View xaml code. it consists of a grid filled with 64 rectangles and 32 images. I have a model-class for the images i would like to bind some properties from to the XMAL-opjects properties. Code in ChessBoardViewModel.cs:

foreach (ChessPiece Piece in ChessPieces)
{
    Image Img = ChessBoard.FindName(Piece.Name) as Image;

    Binding RowBinding = new Binding("Row");
    RowBinding.Source = Piece;
    Img.SetBinding(Grid.RowProperty, RowBinding);

    Binding ColumnBinding = new Binding("Column");
    ColumnBinding.Source = Piece;
    Img.SetBinding(Grid.ColumnProperty, ColumnBinding);
}

Chessboard is the name of the Grid containing all images.

My plan is that the image should be binded to each of the instances Row and Column values to determine where in the game they are.

Problem is that i cannot access the XAML objects for some reason even though i have included the Views namespace.

Edit:

Ok this is my code and how im planning on doing this now:

<Grid x:Name="ChessBoard">
  <Rectangle x:Name="A1" Fill="Black" Grid.Column="1" />
  ...
  ...
  <Image x:Name="BlkRook1" Source="../Data/BlkRook.png" Grid.Row="{Binding ChessBoardViewModel.ChessPieces[0].Row}" Grid.Column="{Binding ChessPieces[0].Column}"/>
 ...   
 </Grid>

and the Viewmodel containing a list of my ChessPieces like this

ChessPieces.Add(new BlkRook() { Name = "BlkRook1", Row = 0, Column = 0 });

And i want to bind the XAML image Grid.Row and Grid.Column property's to the correct instance of my objects. But cant seem to find a way to achieve it.

like image 444
Martin Avatar asked Mar 04 '26 23:03

Martin


1 Answers

WPF is a data-centric language, or at least it works best when it is used in this way. What I mean by that is that we manipulate data objects, not UI objects. So you should never need to access your UI 'board' control, instead Binding a collection to that control and manipulating the items in the collection.

As a short example, you could Bind a collection of 64 items to a UniformGrid, with 32 of them having some field that makes them appear 'empty'. For example, you could have a string property for each item that defines which image to display and the empty squares could have an empty string there.

Then instead of trying to move a UI item from one place in the Grid to another, you can simply move the relevant item in the collection into its new place... for example, if you wanted to move a piece up the board one square, then you'd move it 8 items towards the start of the collection and move the empty piece that was there 8 places towards the end.

like image 91
Sheridan Avatar answered Mar 07 '26 11:03

Sheridan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!