简体   繁体   中英

Binding a method to a column in datagrid WPF

I have a data grid in wpf which is bound to Collection. In one of the columns i want to bind a public method which returns string instead of a property. Is there a way to resolve this in WPF.

By the way its one way binding.

I'm not entirely sure what you want to do and the advice of the previous two answers may be (and probably are more) appropriate in your scenario but just you answer your question, you can indirectly bind to a method using an ObjectDataProvider .

<Window>
  <Window.Resources>
    <ObjectDataProvider x:Key="newGuidProvider"
      ObjectType="{x:Type Guid}"
      MethodName="NewGuid"
      />
  </Window.Resources>

  ...

  <TextBlock Text="{Binding Source={StaticResource newGuidProvider}" ... />

  ...

</Window>

This is just a quick example and you can look into the ObjectDataProvider to see if it's right in your scenario. Here is a great resource which shows additional possibilities such as passing parameters to a method etc., via bindings.

You may be able to accomplish this by using

  • some evil tricks
  • an IValueConverter
  • an attached property
  • a behavior
  • by creating a read only proxy property.

However I'll would recommend using a property. It's the way WPF is supposed to work and handles all UI updating logic for you, too.

Why do you want to bind to a method?

If I right understand what you want, it should be enough to you to implement IValueConverter interface and assign it in XAML to you columns data binding's Converter attribute: here is an example how to use it: WPF Converter Example

for more detailed analysis can have a look on SvnRadar opensource project that use a bunch of them.

EDIT

There is no DataGrid control actually, there is a ListView , but the consept is the same.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM