[英]How to bind a windows form control to data with an IValueConverter
我試圖根據我的數據源中的顏色更改表單控件的背景顏色。 我已經綁定,無需任何轉換即可工作。 如何使用編寫的IValueConverter進行相同操作?
沒有轉換的示例綁定:
this.panel1.DataBindings.Add(new Binding(
"BackColor",
dataSource,
"selectedColor",
false,
DataSourceUpdateMode.OnPropertyChanged));
例如:
<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...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.