使用带有按钮的observablecollection

时间:2013-05-09 16:06:09

标签: c# button observablecollection

我有一个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

1 个答案:

答案 0 :(得分: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);
}