ASP.NET-访问页面上的所有ImageButton并在ImageButton上放置两个图像

本文关键字:ImageButton 图像 两个 并在 NET- ASP 访问 | 更新日期: 2023-09-27 18:21:38

我实际上有两个问题:

(1) 是否可以将另一个图像放在已经设置了ImageUrl的ImageButton上(不更改ImageUrl-实际上只需在"顶部"添加第二个图像)?即使使用CSS?

(2) 我在ListView中包含了一个动态设置的ImageButtons数。当用户单击ImageButton时,我会更改所单击的按钮的.CssClass属性以"突出显示"它。我的问题是:每当单击ImageButton,我不仅需要突出显示它,还需要确保我取消突出显示所有其他按钮。然而,我很难找到其他人。我使用获得点击的ImageButton

((ImageButton)sender).CssClass = "SelectedImageButton";

在事件处理程序中。然而,我如何获得所有其他人,以便将他们的风格"恢复"为未高亮的风格?

提前感谢您的帮助!

更新:已回答我已经使用以下算法解决了(2)中提到的问题。注意,我在下面把@OFConsulting的答案标记为正确答案,因为如果没有他的算法,我永远不会得到下面的算法(这是对他的算法进行了轻微调整)。感谢@OFConsulting!

// Cast the sender to an ImageButton to have the clicked ImageButton
ImageButton clickedImageButton = sender as ImageButton;
// The ListView has ListViewDataItems and the ImageButtons are in 
// THOSE children controls, thus match on the ImageButtons' Parents' IDs
Control parentControl = clickedImageButton.Parent;
List<ListViewDataItem> allOtherImageButtons = MyListView.Controls.OfType<ListViewDataItem().AsQueryable().Where(i => i.ID != clickedImageButton.Parent.ID).ToList();
// Highlight
clickedImageButton.CssClass = "HighlightedStyle";
// Unhighlight
foreach (ListViewDataItem button in allOtherImageButtons)
{
    // The ImageButton is always the 2nd child control of the ListViewDataItem
    ImageButton childImageButton = (ImageButton)button.Controls[1];
    childImageButton.CssClass = "NoHighlightedStyle";
}

ASP.NET-访问页面上的所有ImageButton并在ImageButton上放置两个图像

对于这个问题的第(1)部分,在css类中设置背景图像可能会奏效,但您从未真正解释过为什么不能更改ImageUrl。如果你需要它是动态的,你可以把所有的东西都放在更新面板上,而不需要一堆脚本。

第(2)部分似乎很直接。只需对页面中的相关控件集合使用一点linq即可。

protected void ImageButton5_Click(object sender, ImageClickEventArgs e)
{
    ImageButton clickImageButton = sender as ImageButton;
    // This example assumes all the image buttons have the same parent.
    // Tweak as needed depending on the layout of your page
    Control parentControl = clickImageButton.Parent;
    List<ImageButton> allOtherImageButtons = parentControl.Controls.OfType<ImageButton>().AsQueryable().Where(i => i.ID != clickImageButton.ID).ToList();
    // Highlight
    clickImageButton.CssClass = "WhateverHighlights";
    // Unhighlight
    foreach (ImageButton button in allOtherImageButtons)
    {
        button.CssClass = "WhateverClears";
    }
}

编辑:还有一件事。确保在Page_Load(即初始化期间)之前添加任何动态添加的控件。有些视图状态问题与添加控件太迟有关。