在 Source XAML-attribute of Image 中生成随机数
Generate random number in Source XAML-attribute of Image
作为 Windows 应用程序的一部分(我必须接管),我在 XAML 文件中有以下行:
<Image Grid.Row="1" Grid.Column="5"
x:Name="PART_batterySymbol"
Stretch="Fill"
Source="/CustomControls;component/Resources/Symbol_Battery_2_50x50.png"/>
它在列表框行中显示电池图标:
是否可以在 XAML 中提供一个源代码 ,它会在我拥有的 3 张图像之间随机 select?
- Symbol_Battery_1_50x50.png
- Symbol_Battery_2_50x50.png
- Symbol_Battery_3_50x50.png
我是 WPF 和 C# 的新手,但我有一些 Adobe/Apache Flex 的开发经验,可以在 MXML 文件中嵌入一些代码 通过使用 { .... }
括号
我认为最简单的方法来获得你想要的东西,特别是如果你的图像在深层复杂树中,是这样的:
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}" />
因此,您基本上引用了静态 class 的静态 属性,每次调用此 属性 时,都会 return 电池图标的随机图像。
作为 Windows 应用程序的一部分(我必须接管),我在 XAML 文件中有以下行:
<Image Grid.Row="1" Grid.Column="5"
x:Name="PART_batterySymbol"
Stretch="Fill"
Source="/CustomControls;component/Resources/Symbol_Battery_2_50x50.png"/>
它在列表框行中显示电池图标:
是否可以在 XAML 中提供一个源代码 ,它会在我拥有的 3 张图像之间随机 select?
- Symbol_Battery_1_50x50.png
- Symbol_Battery_2_50x50.png
- Symbol_Battery_3_50x50.png
我是 WPF 和 C# 的新手,但我有一些 Adobe/Apache Flex 的开发经验,可以在 MXML 文件中嵌入一些代码 通过使用 { .... }
括号
我认为最简单的方法来获得你想要的东西,特别是如果你的图像在深层复杂树中,是这样的:
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}" />
因此,您基本上引用了静态 class 的静态 属性,每次调用此 属性 时,都会 return 电池图标的随机图像。