I have a problem with an undesired source update in the OneWayToSource, UpdateSourceTrigger.Explicit scenario
Background: I have a DataGrid containing user data with a password column. I have derived the class DataGridPasswordColumn from DataGridTemplateColumn to
Display some dummy masked data in the non-edit mode (e.g. ####) This is done by setting the CellTemplate to a TextBlock with a constant value:
FrameworkElementFactory frameworkElementFactory = new FrameworkElementFactory(typeof(TextBlock));
frameworkElementFactory.SetValue(TextBlock.TextProperty, Properties.Resources.passwordEncrypted);
CellTemplate = new DataTemplate { VisualTree = frameworkElementFactory };
and to display two PasswordBox controls and an OK-button in the edit mode the following code is used:
FrameworkElementFactory frameworkElementFactory = new FrameworkElementFactory(typeof(PasswordEntry));
Binding bindingPassword = new Binding(propertyNamePassword)
{
Mode = BindingMode.OneWayToSource,
// we only want the target to source binding get activated on explicit request (user clicks on 'OK' button)
UpdateSourceTrigger = UpdateSourceTrigger.Explicit,
// we need to catch and prevent the undesired source update
NotifyOnSourceUpdated = true
};
frameworkElementFactory.SetBinding(PasswordEntry.SelectedPasswordProperty, bindingPassword);
CellEditingTemplate = new DataTemplate { VisualTree = frameworkElementFactory };
PasswordEntry is a user control that
- Has a DependencyProperty named 'SelectedPasswordProperty'
and waits for the user to click the OKButton and then does some validation (are the contents of the two PasswordBoxes identical?). If validation is fine, calls UpdateSource via the following code
BindingExpression be = this.GetBindingExpression(SelectedPasswordProperty); if (be != null) { be.UpdateSource(); }
Updating the source is fine.
The problem is, that when the cell editing template (the PasswordEntry UserControl) is opened there is one undesired source update carrying a value of 'NULL'.
I expected that when UpdateSourceTrigger = UpdateSourceTrigger.Explicit is used, there is no source upda开发者_如何学Cte unless UpdateSource() is called.
I have so far found no way to suppress this source update. I tried
NotifyOnSourceUpdated = true
with
private void PasswordEntry_SourceUpdated(object sender, DataTransferEventArgs dataTransferEventArgs)
{
...
// Cancel this source update
dataTransferEventArgs.Handled = true;
}
but it did not work, i.e. the source was still updated (with a NULL value).
Is this a WPF bug? Has anybody had the same problem?
I found out that using TwoWay binding solves my problem and does not do the unexpected source update. I still however do not really understand why this initial target to source update is done. I presume there is a technical reason for this.
精彩评论