我试图根据数据源中的颜色更改表单控件的背景颜色。我没有任何转换就能使绑定工作。 如何使用我写过的IValueConverter来做同样的事情?
没有转换的示例绑定:
this.panel1.DataBindings.Add(new Binding(
"BackColor",
dataSource,
"selectedColor",
false,
DataSourceUpdateMode.OnPropertyChanged));
答案 0 :(得分:0)
例如:
<UserControl myControls="clr-namespace:MyProjectRef">
<UserControl.Resources>
<myControls:MyValueConverter x:Key="myConverter"/>
</UserControl.Resources>
<Grid Background="{Binding MyCurrentBackgroundProperty, Converter={StaticResource myConverter}}"/>
</UserControl>
编辑1:
抱歉,我没有看到这是Windows窗体问题。
使用绑定上的Format和Parse事件来有效创建数值转换器。
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...
}