简体   繁体   中英

Winforms Databinding with a custom setter

I'm using some good old fashing DataBinding in a Winforms project.

I have my form with a control (A devExpress RichTextEdit for those that want to know)

I want to bind the HtmlText property of the richTextEdit control to a property on my ViewModel

I have done that binding and that is not a problem. However I have realised that the HtmlText that comes out of the richTextEdit is HtmlEncoded. Meaning that characters get encoded into their html entity representation. eg < becomes &lt; etc

I don't want this to happen as those tags have special meaning further down the line and I need to keep them.

So in my ViewModel that has all the notify property changed stuff and essentially wraps my domain object I could do this

public class ViewModel: INotifyPropertyChanged
{
    public string WrappedProperty
    {
        get => domainObject.Property;
        set
        {
            domainObject.Property = HttpUtility.DecodeHtml(value);
            //Raise Property changed event etc
        }
    }
}

and in my form I create a Data binding

Binding binding = new Binding("HtmlText", _viewModel, "WrappedProperty", true, DataSourceUpdateMode.OnPropertyChanged,null,null);
_richEditControl.DataBindings.Add(binding);

now this works as intended, however I don't like it. My view model is doing things because of the control I am currently using. Its 'leaky' and it smells.

I want my View to be handle view specific issues.

What I'd like to do is to create a binding between the controls Html Text property and my View models WrappedProperty property, providing a custom function to be used when setting the property from the control into the view model. Is is something that can be implemented or is there some kind of common work around pattern that I am missing?

Thanks

You can handle this in the binding using the Parse event.

Binding binding = new Binding("HtmlText", _viewModel, "WrappedProperty", true, DataSourceUpdateMode.OnPropertyChanged,null,null);
binding.Parse += (sender, e) => e.Value = HttpUtility.DecodeHtml(e.Value);
_richEditControl.DataBindings.Add(binding);

I managed to discover this myself, but as I struggled to find anything for a while on google about this I thought'd I'd myself and hopefully help future developers

There is an event on a Binding called Parse. Subscribing to this event allows to you to work with the value before it gets sent back to the data source.

Its partner is the Format event this allows you to work the value before it is displayed in the control

https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.binding.parse?view=netframework-4.8

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