按名称设置并查找控件

本文关键字:查找 控件 设置 | 更新日期: 2023-09-27 18:27:28

我只有这个,它运行良好:

if (direction.Equals("UR"))
{
    UR_Image.Source = new BitmapImage(new Uri(String.Format("file:///{0}/../Family/" + name + "/Image/"+direction+".png", Directory.GetCurrentDirectory())));
}
else if (direction.Equals("UL"))
{
    UL_Image.Source = new BitmapImage(new Uri(String.Format("file:///{0}/../Family/" + name + "/Image/"+direction+".png", Directory.GetCurrentDirectory())));
}

我想做的是下面,写为伪代码:

direction + _Image.Source = new BitmapImage(new Uri(
    String.Format("file:///{0}/../Family/" + name + "/Image/"+direction+".png", 
    Directory.GetCurrentDirectory())));

如何实现direction + _Image

Direction是string,UL_Image和UR_Image是图像视图。

按名称设置并查找控件

尝试以下方法。

YourWindow.xaml

<!-- named controls -->
<Image x:Name="ImageOne" />
<Image x:Name="ImageTheOther" />

YourWindow.xaml.cs

// get image control by name
var control = FindName(string.Format("Image{0}", direction)) as Image;
if (control == null)
    return;
// set bitmap once
string path = Path.Combine(Environment.CurrentDirectory, "image.png");
var bitmap = new BitmapImage(new Uri(path));
// assign
control.Source = bitmap;

其中direction是枚举

public enum Direction
{
    One,
    TheOther
}