WPF 绑定到方法背后的代码

Mat*_*t B 2 wpf binding code-behind

这很烦人 - 我知道我会如何在网络上做到这一点......

我有一个 wpf 图像,我想将它的源属性绑定到一个方法,并从它的绑定项中传入一个属性。

IE。

<image source="GetMySource({binding name})" />
Run Code Online (Sandbox Code Playgroud)

GetMySource 在哪里

protected string GetMySource(string name)
{
return "images/"+name+".png";
}
Run Code Online (Sandbox Code Playgroud)

Aur*_*bon 5

这就是 .NET 不使用方法返回简单对象,而是使用 CLR 属性的原因。您是按照 Java 风格进行操作,而不是 .NET 风格。

public string MySource {
  get { return "images/" + name + ".png"; }
}
Run Code Online (Sandbox Code Playgroud)

现在该属性已公开,您有一些选择:

  1. 您的DataBind以自身(在构造函数:DataContext = this;

    < Image source="{Binding MySource}" />

  2. 命名您的 UserControl(或其他)( <UserControl x:name="this" ...>)

    < Image source="{Binding MySource, ElementName=this}" />

  3. 使用相对源绑定

    < Image source="{Binding MySource, RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl}" />

编辑 :

如果我理解得很好,实际上您想使用参数(此处为图像的名称)进行绑定。你不能。只有命令绑定才允许使用 CommandParameter。您可以使用许多声明为 ObjectDataProvider 或转换器的资源,但这对于您的简单工作来说开销太大。

您的简单解决方案:为所有图像使用一个数组,并单向绑定到该数组的各个对象。

private string[] mysource = new[] {
  "images/foo.png", 
  "images/bar.png", 
  "images/baz.png"};
public string[] MySource {
  get { return mySource; }
}
Run Code Online (Sandbox Code Playgroud)
  1. 您的DataBind以自身(在构造函数:DataContext = this;

    < Image source="{Binding MySource[0]}" />

    1. ...等等。

我没有测试它,但下面文章中的那个人做了:http : //www.codeproject.com/Articles/37352/WPF-Binding-to-individual-collection-items-but-not.aspx