我有统一的网格,带有按钮和标签。每个按钮都有独特的内容,点击框中的按钮,我想在此框中更改标签。但是我如何弄清楚单击了哪个框按钮以及需要更改哪个标签?
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>
答案 0 :(得分:0)
我会通过&#34;呼叫&#34; StructOfBox作为ChangeAmount()处理程序的参数。这样你就可以在不需要知道点击了哪个按钮的情况下更改标签。
但正如Clemens所说,为了使其正常工作,StructOfBox必须实现INotifyPropertyChanged。