The lack of questions on the subject may be an indication of code smell here, but... Is it possible to write an extension method for a class and databind to that like you would a property?
The assumption is that I am provided with a class structure that I'm not able to fundamentally change, but I want to express a series of its boolean properties as a string for display purposes.
Simplified base class:
public class Transmission
{
public int ID { get; set; }
public bool Cancelled { get; set; }
public bool Stored { get; set; }
public bool Recorded { get; set; }
}
My extension method:
public static class Extensions
{
public static string Status(this Transmission trans)
{
StringBuilder sb = new StringBuilder("|");
if (trans.Cancelled)
sb.Append("| Cancelled ");
if (trans.Recorded)
sb.Append("| Recorded ");
if (trans.Stored)
sb.Append("| Stored ");
sb.Append("||");
return sb.ToString();
}
}
To add further complexity, I'm being passed a list of these things, and I'm trying to bind to a datagrid (with severely limited XAML experience).
<GroupBox Header="Here is an amazing list of results for you to violate horribly.">
<DataGrid ItemsSource="{Binding Transmissions, Mode=OneWay}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Width="*" Header="Local ID" Binding="{Binding ID, Mode=OneWay}"/>
<DataGridTextColumn Width="*" Header="Status" Binding="{Binding Status, Mode=OneWay}"/>
</DataGrid.Columns>
</DataGrid>
</GroupBox>
I've tested the code and was able to bind to ID without any difficulty. The 'Status' however, is not being picked up at all. Is there a trick to binding to an extension property? Or would it be more prudent to just write a decorator/facade class and bind to that?
That is what you usually use a pattern like MVVM for. You add properties to the view-model which are based on the model and only relevant to the view. The view-model can contain a reference to the model to either bind directly to its properties or to mirror them on the view-model (for decoupling i would opt for the latter).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With