【问题标题】:C# working with button when button name is in a list当按钮名称在列表中时,C# 使用按钮
【发布时间】:2016-03-26 16:33:00
【问题描述】:

我从列表中创建了几个按钮,我现在需要更改其中一个按钮的图像。 我现在正在尝试将字符串转换为按钮。 我如何获取字符串并将其转换为我可以使用的按钮?

我试过这个:

Button button = (Button)this.FindName("button_" + list[0].ToString()); button.background = brush;

当我调用 button.background 时,我得到一个对象引用未设置为对象实例的错误。

编辑 这就是我选择更改按钮图像的方式:

Uri resourceUri = new Uri("led_On.png", UriKind.Relative);
        StreamResourceInfo streamInfo = Application.GetResourceStream(resourceUri);

        BitmapFrame temp = BitmapFrame.Create(streamInfo.Stream);
        var brush = new ImageBrush();
        brush.ImageSource = temp;

        Button button = (Button)FindName("button_" + list[0].ToString());

        button.Background = brush;

我只是无法抓住名称为 button_list[0] 的按钮。

【问题讨论】:

  • 什么是“这个”?这个按钮是这个的孩子吗?

标签: c# wpf button


【解决方案1】:

下面列出了在 Click 事件 (C#) 上更改 WPF 按钮 Image 的一种可能解决方案:

清单 1. 单击时更改按钮图像 (XAML)

<Button Name ="button1" Click="button1_Click">
    <Button.Template>
        <ControlTemplate TargetType="Button">
            <Image x:Name="image1">
                <Image.Style>
                    <Style TargetType="{x:Type Image}">
                        <Setter Property="Source"  Value="Images/ContentImage.png" />
                    </Style>
                </Image.Style>
            </Image>
        </ControlTemplate>
    </Button.Template>
</Button>

清单 2. 后面的 C# 代码(button1.click 事件处理程序)

private void button1_Click(object sender, RoutedEventArgs a)
{
    Image _img= button1.Template.FindName("image1", button1) as Image;
    Style _imgStyle = new Style { TargetType = typeof(Image) };
     _imgStyle.Setters.Add(new Setter(Image.SourceProperty, new BitmapImage(new Uri(@"pack://application:,,,/YourAssemblyName;component//Images/ContentImage1.png"))));
    _img.Style = _imgStyle;
}

与您的代码相关,可以以简单的形式重写:

StreamResourceInfo _streamInfo = 
Application.GetResourceStream(new Uri("led_On.png", UriKind.Relative));

button.Background = (new ImageBrush(){ImageSource=BitmapFrame.Create(_streamInfo.Stream)});

只要确保button 对象不为空(检查此语句:"button_" + list[0] - 可能只是列表[0]?)

希望这会有所帮助。

【讨论】:

  • 谢谢,但我只是想把我的字符串列表放入我可以更改属性的按钮中。
  • 请参考我的扩展答案。最好的问候,
  • 所以我想这解决了我的问题,为什么按钮为空?我做了一个检查,它是空的。我都将使用您的简化代码来更改我的按钮图像。谢谢
  • 如果您指定正确的按钮名称(按钮必须在该检查之前存在),这应该可以工作。请标记已接受的答案,并随时发布其他问题。最好的问候,
猜你喜欢
  • 2019-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-09
  • 2023-03-31
  • 1970-01-01
  • 2021-01-30
相关资源
最近更新 更多