Pass Value through Data Binding to Code
I am currently working on a chess game and I am trying to connect the C# code-behind to the WPF interface in XAML. To represent the chess board, I have created an 8x8 uniform grid. I want to pass the name of the square (cell of the grid) to the code behind and then have a method return the path of the image of the appropriate piece. For example, if there is a white rook on the square a8, this will be saved in the code-behind. In the xaml, each square will pass its name (eg 'a8') and receive the path to the image of the white rook. If there is no piece on the square, the path will link to a transparent image. This is what I have got so far:
<StackPanel Height="auto" Width="auto" Orientation="Vertical" Margin="-5,0,5,0" >
<UniformGrid Rows="8" Columns="8" Background="Black" Height="800" Width="800" HorizontalAlignment="Stretch">
<StackPanel Orientation="Vertical" Margin="1,1,1,1">
<Image Source="Resources/WhiteSquare.png"/>
<Image Source=""/>
<!--{Bind path to method in code-behind; pass name (e.g. a8); function then returns path to appropriate image of piece-->
</StackPanel>
</UniformGrid>
</StackPanel>
I would appreciate some inspiration both for my xaml and c#. Thank you!
You should probably look into the MVVM design pattern: https://msdn.microsoft.com/en-us/library/hh848246.aspx. It is the recommended design pattern to use when building XAML based UI applications.
But to pass a name of an element that you have defined in your XAML markup to the code-behind you could handle the Loaded
event of the element. You could for example set the Tag
property of the Image
to "a8" and handle is Loaded
event in the code-behind something like this:
<UniformGrid Rows="8" Columns="8" Background="Black" Height="800" Width="800" HorizontalAlignment="Stretch">
<StackPanel Orientation="Vertical" Margin="1,1,1,1">
<Image Source="Resources/WhiteSquare.png"/>
<Image Tag="a8" Loaded="Img_Loaded" />
</StackPanel>
</UniformGrid>
private void Img_Loaded(object sender, RoutedEventArgs e)
{
Image img = sender as Image;
string name = img.Tag.ToString();
//set source of Image based on the value of name here...
//see for an example http://stackoverflow.com/questions/350027/setting-wpf-image-source-in-code
}
链接地址: http://www.djcxy.com/p/84600.html
上一篇: 国际象棋生成可能的移动国王安全
下一篇: 通过数据绑定将代码传递给代码