【问题标题】:Generate random number in Source XAML-attribute of Image在图像的源 XAML 属性中生成随机数
【发布时间】:2015-09-23 21:22:35
【问题描述】:

作为 Windows 应用程序的一部分(我必须接管),我在 XAML 文件中有以下行:

<Image Grid.Row="1" Grid.Column="5" 
  x:Name="PART_batterySymbol"
  Stretch="Fill" 
  Source="/CustomControls;component/Resources/Symbol_Battery_2_50x50.png"/>

它在 ListBox 行中显示一个电池图标:

是否可以在 XAML 中提供一个源代码,它会在我拥有的 3 个图像之间随机选择?

  • Symbol_Battery_1_50x50.png
  • Symbol_Battery_2_50x50.png
  • Symbol_Battery_3_50x50.png

我是 WPF 和 C# 的新手,但我有一些使用 Adob​​e/Apache Flex 的开发经验,并且可以使用 { .... } 括号将一些代码 嵌入到 MXML 文件中 文件中

【问题讨论】:

  • 那么使用转换器不是您的选择吗?默认情况下,您不能将代码直接放在 xaml 中,也不应该这样做。
  • 我试过 Source="Symbol_Battery_&lt;![CDATA[ 2 ]]&gt;_50x50.png"... 什么是“转换器”?
  • Is it please possible to have a source code inside of XAML which would randomly select between the 3 images I have? source code inside of XAML 到底是什么意思? “是否可以在 xaml 中编写多个图像之间的切换逻辑而无需任何代码隐藏?” - 这就是你要问的吗?
  • 我很想切换 .cs 文件中的逻辑 - 但不知道如何访问它(涉及一些晦涩的自定义控件)...
  • 好吧,按照我的看法:您可以为该图像制作样式并制作事件触发器,这将在某些事件触发时切换源。问题是,事件将是什么。它可能正在更改基础数据或用户输入事件。但我看不到只能在 xaml 中 随机 做到这一点

标签: wpf xaml wpf-controls


【解决方案1】:

我认为获得你想要的最简单的方法是:

public static class BatteryIcons {
    private static readonly Random _random = new Random();
    public static ImageSource Random {
        get
        {
            var id = _random.Next(1, 4);
            // read random icon from your resources given id and return
            // alternatively, use default ImageSourceConverter
            string path = "get path to your icon";
            return (ImageSource) new ImageSourceConverter().ConvertFromString(path);
        }
    }
}

然后在你的 xaml 中:

<Image Source="{x:Static wpf:BatteryIcons.Random}" />

所以你基本上引用了静态类的静态属性,每次调用这个属性都会返回你的电池图标的随机图像。

【讨论】:

    猜你喜欢
    • 2018-03-10
    • 2014-07-03
    • 1970-01-01
    • 1970-01-01
    • 2012-03-13
    • 1970-01-01
    • 1970-01-01
    • 2021-11-05
    • 2014-10-14
    相关资源
    最近更新 更多