Binding to a property of an object through object[property] rather than object.property

与世无争的帅哥 提交于 2019-12-24 19:12:58

问题


I've read through the WPF Data Binding Overview and I feel like this should be possible but I can't quite make the mental leap here. I know that if I set a binding's Path to foo, and set the Source to obj, then the binding will look at obj.foo. In other words, obj.__getattr__() will be accessed.

All I want is to make it look at obj[foo] instead. I'm using Ironpython and in this case my obj class has an overridden __getitem__() that calls a member function and returns a value, which is why I need this functionality.

Here is the above example written programmatically. This displays the foo property of obj in a checkbox:

myBinding = Binding("foo")
myBinding.Source = obj          
acheckbox.SetBinding(CheckBox.IsCheckedProperty, myBinding)

Solution

It's as simple as this, apparently!

myBinding = Binding("[foo]")
myBinding.Source = obj          
acheckbox.SetBinding(CheckBox.IsCheckedProperty, myBinding)

回答1:


You can just use that in a binding, e.g. if my DataContext/source has a property

public string this[int i]
{
    get{...}
    set{...}
}

you can create a binding like this:

<TextBlock Text="{Binding [0]}"/>

Edit: I feel like i might have misunderstood your question, if so please tell me.



来源:https://stackoverflow.com/questions/4947758/binding-to-a-property-of-an-object-through-objectproperty-rather-than-object-p

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!