0

我有一个 observablecollection 来创建按钮问题是这些按钮中的每一个都调用相同的事件处理程序。我正在努力使每个按钮都有自己唯一的 id,以便彼此区分开来。用于创建按钮元素的代码是

public class button
{
    public bool IsEmpty { get; set; } 
    public int ID {get; set;}

    public button(int button_Number)
    {
        IsEmpty = true;
        ID = button_Number;

    }
}

我被添加到以下代码中的 observablecollection

        ButtonCollection = new ObservableCollection<cChipVM>();

        for ( int i = 0 ; i < iNumChips ; ++i )
        {
            ButtonCollection.Add( new button(i) );

        }

按钮的xml如下

 <DataTemplate x:Key="ButtonTemplate">
        <Button x:Name="Button" Uid="{Binding Path=ID}" Click="Button_Click" BorderBrush="Black" BorderThickness="1" Margin="7" Width="25" Height="25" ClickMode="Press" Opacity="0.9" Focusable="False" IsHitTestVisible="True" AllowDrop="True" IsTabStop="False">
            <Button.Style>                    
                <Style>
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding Path=IsEmpty}" Value="false">
                            <Setter Property="Button.Background">
                                <Setter.Value>
                                    <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                                        <GradientStop Color="#FF5ED426" Offset="0"/>
                                        <GradientStop Color="White" Offset="1"/>
                                    </LinearGradientBrush>
                                </Setter.Value>
                            </Setter>
                        </DataTrigger>
                        <DataTrigger Binding="{Binding Path=IsEmpty}" Value="true">
                            <Setter Property="Button.Background">
                                <Setter.Value>
                                    <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                                        <GradientStop Color="#FF1766F0" Offset="0"/>
                                        <GradientStop Color="White" Offset="1"/>
                                    </LinearGradientBrush>
                                </Setter.Value>
                            </Setter>
                        </DataTrigger>

                    </Style.Triggers>
                </Style>
            </Button.Style>
        </Button>
    </DataTemplate>

当它尝试使用此方法设置 Uid 时,系统崩溃,任何建议如何解决此问题或任何其他解决方案,其中每个按钮都可以具有唯一 ID

4

1 回答 1

1

您可以使用 Button.Tag 属性来存储 ID 并在处理程序中检查 Tag 的值

<Button Tag="{Binding Path=ID}" Click="Button_Click" BorderBrush="Black" BorderThickness="1" Margin="7" Width="25" Height="25" ClickMode="Press" Opacity="0.9" Focusable="False" IsHitTestVisible="True" AllowDrop="True" IsTabStop="False">

更新:按钮点击处理程序

public void Button_Click(object sender,EventArgs e)
{ 
      var myButton = (Button)sender;
      int id = Convert.ToInt32(myButton.Tag);
}
于 2013-05-09T16:16:26.193 回答