按名称设置和查找控件

时间:2014-10-22 09:36:45

标签: c# wpf visual-studio

我拥有的是它,它的工作正常:

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是图像视图。

1 个答案:

答案 0 :(得分:1)

尝试以下方法。

<强> 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
}