简体   繁体   中英

How to bind a windows form control to data with an IValueConverter

I'm trying to change the background color of a form control based on a color in my datasource. I've got the binding to work without any conversion. How to I use an IValueConverter I've written to do the same?

Example Binding without conversion:

this.panel1.DataBindings.Add(new Binding(
                "BackColor",
                dataSource,
                "selectedColor",
                false,
                DataSourceUpdateMode.OnPropertyChanged));

For example:

<UserControl myControls="clr-namespace:MyProjectRef">

    <UserControl.Resources>

        <myControls:MyValueConverter x:Key="myConverter"/>

    </UserControl.Resources>

    <Grid Background="{Binding MyCurrentBackgroundProperty, Converter={StaticResource myConverter}}"/>

</UserControl>

EDIT 1:

Sorry, I failed to see this is a Windows Forms issue.

Use the Format and Parse events on your binding to effectively create your value converter.

Binding backgroundBinding = new Binding("BackColor", dataSource, "selectedColor", false, DataSourceUpdateMode.OnPropertyChanged);

backgroundBinding.Parse += OnParseBackgroundBinding;
backgroundBinding.Format += OnFormatBackgroundBinding;

this.panel1.DataBindings.Add(backgroundBinding);

private void OnParseBackgroundBinding(object sender, ConvertEventArgs args)
{
    // this is called when the value of the binding changes
    Color background = (Color)args.Value;

    // do your conversion here...
    args.Value = ...
}

private void OnFormatBackgroundBinding(object sender, ConvertEventArgs args)
{
    // this is called when the property of the binding changes

    // do conversion here if necessary...
}

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