1

我在 OneWayToSource、UpdateSourceTrigger.Explicit 场景中遇到了不需要的源更新问题

背景:我有一个包含用户数据和密码列的 DataGrid。我已经从 DataGridTemplateColumn 派生了类 DataGridPasswordColumn 到

在非编辑模式下显示一些虚拟屏蔽数据(例如####)这是通过将 CellTemplate 设置为具有常量值的 TextBlock 来完成的:

FrameworkElementFactory frameworkElementFactory = new FrameworkElementFactory(typeof(TextBlock));
frameworkElementFactory.SetValue(TextBlock.TextProperty, Properties.Resources.passwordEncrypted);
CellTemplate = new DataTemplate { VisualTree = frameworkElementFactory };

并在编辑模式下显示两个 PasswordBox 控件和一个 OK 按钮,使用以下代码:

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 是一个用户控件

  • 有一个名为“SelectedPasswordProperty”的 DependencyProperty
  • 并等待用户单击 OKButton,然后进行一些验证(两个 PasswordBox 的内容是否相同?)。如果验证没问题,通过以下代码调用 UpdateSource

    BindingExpression = this.GetBindingExpression(SelectedPasswordProperty); if (be != null) { be.UpdateSource(); }

更新源码就好了。

问题是,当打开单元格编辑模板(PasswordEntry UserControl)时,会出现一个带有“NULL”值的不需要的源更新。

我预计当使用 UpdateSourceTrigger = UpdateSourceTrigger.Explicit 时,除非调用 UpdateSource(),否则不会更新源。

到目前为止,我还没有找到抑制此源更新的方法。我试过了

NotifyOnSourceUpdated = true

private void PasswordEntry_SourceUpdated(object sender, DataTransferEventArgs dataTransferEventArgs)
{
    ...
    // Cancel this source update
    dataTransferEventArgs.Handled = true;   
}

但它不起作用,即源仍被更新(使用 NULL 值)。

这是 WPF 错误吗?有没有人有同样的问题?

4

1 回答 1

0

我发现使用 TwoWay 绑定可以解决我的问题并且不会进行意外的源更新。然而,我仍然不明白为什么要完成这个初始目标到源更新。我认为这是有技术原因的。

于 2011-04-21T06:40:22.477 回答