开发者

WPF Binding to code behind methods

This is annoying - I know how I'd do it in web...

I have a wpf image and I want to bind it's source property to a method, and pass in a property from it's bound item.

IE.

<image source开发者_JS百科="GetMySource({binding name})" />

Where GetMySource is

protected string GetMySource(string name)
{
return "images/"+name+".png";
}


This is the reason .NET does not use methods to return simple objects, but CLR properties. You're doing it the Java style, not the .NET style.

public string MySource {
  get { return "images/" + name + ".png"; }
}

Now the property is exposed, you have some choices :

  1. DataBind your view to itself (in constructor : DataContext = this;)

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

  2. Name your UserControl (or whatever) (<UserControl x:name="this" ...>)

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

  3. Use relativesource binding

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

EDIT :

If I understand well, actually you want to do a binding with a parameter (the name of the image here). You can't. Only Command bindings allows a CommandParameter. You could use many resource declared ObjectDataProviders, or Converters, but that's too much overhead for your simple job.

Your simple solution : use an array for all your images, and one-way bind to the individual objects of this array.

private string[] mysource = new[] {
  "images/foo.png", 
  "images/bar.png", 
  "images/baz.png"};
public string[] MySource {
  get { return mySource; }
}
  1. DataBind your view to itself (in constructor : DataContext = this;)

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

    1. ...etc.

I did not test it, but the man from the following article did : http://www.codeproject.com/Articles/37352/WPF-Binding-to-individual-collection-items-but-not.aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜