יום ראשון, 17 באפריל 2011

WPF - Manually Update Binding Source


When we use binding, we can couple of ways of data binding: 

* OneWay
* Two Way
* OneWayToSource
OneTime


And, there are several UpdateSourceTriggers:

* LostFocus
* PropertyChanged
* Explicit

You can find all details information here: http://msdn.microsoft.com/en-us/library/ms752347.aspx#basic_data_binding_concepts

XAML for example:

<ComboBox Name="comboHour" ItemStringFormat="HH:mm" 
                           SelectedValue="{Binding EnteredOnTime, 
                                           Mode=TwoWay, 
                                           UpdateSourceTrigger=Explicit}" 
                           Background="#0E0000FF"  
                           Width="70" 
                           HorizontalAlignment="Left"/>



public static void UpdateItemSource(FrameworkElement item)
        {
            FieldInfo[] infos = item.GetType().GetFields(BindingFlags.Public | BindingFlags.Fl            attenHierarchy | BindingFlags.Instance | BindingFlags.Static);
            foreach (FieldInfo field in infos)
            {
                if (field.FieldType == typeof(DependencyProperty))
                {
                    DependencyProperty dp = (DependencyProperty)field.GetValue(null);
                    BindingExpression ex = item.GetBindingExpression(dp);
                    if (ex != null)
                    {                        
                      if(ex.ParentBinding.UpdateSourceTrigger == UpdateSourceTrigger.Explicit)
                         ex.UpdateSource();
                    }
                }
            }
          
            int count = VisualTreeHelper.GetChildrenCount( item);
            for (int i = 0; i < count; i++)
            {
              FrameworkElement child = VisualTreeHelper.GetChild(item, i) as FrameworkElement;
                if(child != null)
                    UpdateItemSource(child);
            }
        }    

אין תגובות:

הוסף רשומת תגובה