private void MapTile_MouseDown(object sender, MouseButtonEventArgs e) { Rectangle mapSquare = sender as Rectangle; var row = Grid.GetRow(mapSquare); var column = Grid.GetColumn(mapSquare); var existingTile = ViewModel.Map.GetTileAt(ViewModel.CurrentLevel, row, column); if (e.ChangedButton == MouseButton.Left && ViewModel.SelectedTile != null) { //if this tile already exists, update it. Otherwise, add if (existingTile != null) { Tile newTile = ViewModel.SelectedTile.Clone(); //overlay the tile, so that transparency looks good existingTile.Tile.LayTileOver(newTile); } else { var newTile = new MapTile(ViewModel.CurrentLevel, row, column, ViewModel.SelectedTile.Clone()); ViewModel.Map.MapTiles.Add(newTile); AddMapTile(newTile); } } if (e.ChangedButton == MouseButton.Right) { //remove the tile from the map if (existingTile != null) { ViewModel.Map.MapTiles.Remove(existingTile); } //remove the child from the map referenced by the existing tile, not necessarily who handled the click event UIElement toRemove = null; foreach (UIElement element in MapGrid.Children) { var elementCast = element as Rectangle; if (elementCast != null && elementCast.DataContext != null && elementCast.DataContext == existingTile) { toRemove = element; break; } } if (toRemove != null) { MapGrid.Children.Remove(toRemove); } } }
private void AddMapTile(MapTile mapTile) { var toAdd = CreateMapTile(mapTile); MapGrid.Children.Add(toAdd); }
private Rectangle CreateMapTile(MapTile mapTile) { //create the rectangle var toReturn = new Rectangle { Width = 50, Height = 50, StrokeThickness = .1, Stroke = new SolidColorBrush(Colors.White), SnapsToDevicePixels = true }; RenderOptions.SetBitmapScalingMode(toReturn, BitmapScalingMode.NearestNeighbor); toReturn.MouseDown += MapTile_MouseDown; Grid.SetRow(toReturn, mapTile.Row); Grid.SetColumn(toReturn, mapTile.Column); Panel.SetZIndex(toReturn, mapTile.Level); //create the data context toReturn.DataContext = mapTile; //create the binding for the fill, and bind to Tile.CurrentFrame.BitmapSource var binding = new Binding("Tile.CurrentFrame.BitmapSource"); binding.Source = toReturn.DataContext; var brush = new ImageBrush(); BindingOperations.SetBinding(brush, ImageBrush.ImageSourceProperty, binding); toReturn.Fill = brush; var visibilityBinding = new MultiBinding(); visibilityBinding.Converter = new MapTileVisibilityConverter(); visibilityBinding.Bindings.Add(new Binding("DisplayAllLevels") { Source = ViewModel }); visibilityBinding.Bindings.Add(new Binding("CurrentLevel") { Source = ViewModel }); visibilityBinding.Bindings.Add(new Binding("Level") { Source = toReturn.DataContext }); visibilityBinding.NotifyOnSourceUpdated = true; toReturn.SetBinding(VisibilityProperty, visibilityBinding); return toReturn; }