Wpf统一网格项

本文关键字:网格 Wpf | 更新日期: 2023-09-27 18:05:47

我有一个统一的网格,带有按钮和标签。每个按钮都有独特的内容,点击按钮后位于框我想改变标签在这个框。但是我怎么知道哪个框按钮被点击了,哪个标签需要改变?

namespace WpfApplication107
{
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new Shop();
    }
}
public class StructOfBox
{
    public string Size { get; set; }
    public string Amount { get; set; }
    public ICommand ChangeSize { get; set; }
}
public class Shop
{
    public Shop()
    {
        Items = new ObservableCollection<StructOfBox>();
        Items.Add(new StructOfBox { Amount = "0", Size = "S", ChangeSize = new RelayCommand(() => ChangeAmount()) });
        Items.Add(new StructOfBox { Amount = "0", Size = "M", ChangeSize = new RelayCommand(() => ChangeAmount()) });
        Items.Add(new StructOfBox { Amount = "0", Size = "L", ChangeSize = new RelayCommand(() => ChangeAmount()) });
        Items.Add(new StructOfBox { Amount = "0", Size = "XL", ChangeSize = new RelayCommand(() => ChangeAmount()) });
    }
    public ObservableCollection<StructOfBox> Items { get; set; }
    public void ChangeAmount()
    {
        // what box?
        Debug.WriteLine("pressed");
    }
}
}
Xaml:

 <Grid>
    <ItemsControl ItemsSource="{Binding Items}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <UniformGrid Columns="2" Rows="2"></UniformGrid>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Border BorderThickness="2" BorderBrush="Green">
                    <Grid>
                        <Grid.RowDefinitions>
                            <RowDefinition></RowDefinition>
                            <RowDefinition></RowDefinition>
                            <RowDefinition></RowDefinition>
                        </Grid.RowDefinitions>
                        <Button Content="{Binding Size}" Command="{Binding ChangeSize}"></Button>
                        <Label Content="{Binding Amount}" Height="25" Grid.Row="2"></Label>
                    </Grid>
                </Border>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</Grid>

Wpf统一网格项

我将把"calling" StructOfBox作为参数传递给ChangeAmount()处理程序。这样,您就可以更改标签,而不需要知道单击了哪个按钮。

但正如Clemens所说,为了使其正常工作,StructOfBox将不得不实现INotifyPropertyChanged。