我有一个Grid 5x4,我放置按钮,稍后我将添加图片。我需要知道这个按钮在这个网格中的位置,所以我可以用这个Plus图像替换添加的图片。或者,如果我选择多张图片,要知道从哪个位置填充网格。这是我的网格和模板:
<Grid>
<ItemsControl x:Name="myItems" >
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Grid HorizontalAlignment="Left" VerticalAlignment="Top" Margin="10,50,0,0" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*" />
<ColumnDefinition Width="1*" />
<ColumnDefinition Width="1*" />
<ColumnDefinition Width="1*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="1*" />
<RowDefinition Height="1*" />
<RowDefinition Height="1*" />
<RowDefinition Height="1*" />
<RowDefinition Height="1*" />
</Grid.RowDefinitions>
</Grid>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Click="Add_Picture">
<Border Width="100" Height="100" BorderThickness="1" BorderBrush="Black" Margin="3" Padding="5">
<!-- <Canvas Margin="-1,-1,0,0" Width="90" Height="90" Name="cCanvas" MouseDown="cCanvas_MouseDown">-->
<Canvas Margin="-1,-1,0,0" Width="90" Height="90" Name="cCanvas">
<Canvas.Background>
<ImageBrush Stretch="UniformToFill" ImageSource="{Binding ImagePath}"/>
</Canvas.Background>
<!-- <Grid Name="SquareSelectedIndicator" Visibility="{Binding IsSelected, Converter={StaticResource BoolToVis}, FallbackValue=Hidden}" Width="30" Height="30" >-->
</Canvas>
<Border.Style>
<Style TargetType="{x:Type Border}">
<Setter Property="BorderBrush"
Value="Black" />
<Style.Triggers>
<Trigger Property="IsMouseOver"
Value="True">
<Setter Property="BorderBrush"
Value="Red" />
</Trigger>
</Style.Triggers>
</Style>
</Border.Style>
</Border>
</Button>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
答案 0 :(得分:1)
我尝试了你的代码并没有产生你发布的视图。所有按钮位于彼此相同的位置。
要获取您发布的视图,我使用UniformGrid
作为ItemsPanel,Columns
值为4.
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="4" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
知道这一点你可以像这样使用Add_Picture处理程序:
private void Add_Picture(object sender, RoutedEventArgs e)
{
Button clickedButton = sender as Button;
if (clickedButton != null)
{
object displayedItem = clickedButton.DataContext;
int index = this.myItems.Items.IndexOf(displayedItem);
int x = index % 4;
int y = index / 4;
MessageBox.Show("x: " + x + " | y: " + y);
}
}
让我知道这是否符合您的需求。