You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF中使用TargetUpdated报错:无法绑定目标方法的问题求助

WPF TargetUpdated事件绑定报错:签名不兼容问题

问题场景

尝试在WPF中使用TargetUpdated功能,编写了以下XAML代码:

<TextBlock TargetUpdated="QuantityRequested_TargetUpdated">
  <TextBlock.Text>
    <MultiBinding StringFormat="{}{0} Quantity {1} {2}">
      <Binding Path="ProductName" NotifyOnTargetUpdated="True"/>
      <Binding Path="QuantityRequested" NotifyOnTargetUpdated="True"/>
      <Binding Path="PreCouponQtyAdjPrice" NotifyOnTargetUpdated="True"/>
    </MultiBinding>
  </TextBlock.Text>
</TextBlock>

对应的后台处理方法:

public partial class CheckoutView : UserControl
{
    /* 省略其他代码 */

    public void QuantityRequested_TargetUpdated(
        Object sender, DataTransferEventArgs args)
    {
    }
}

运行时抛出错误:

System.Windows.Markup.XamlParseException
  HResult=0x80131501
  Message=Failed to create a 'TargetUpdated' from the text 'QuantityRequested_TargetUpdated'.
  Source=PresentationFramework
...
Inner Exception 1:
ArgumentException: Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type.

注:已按照@BionicCode的建议修改代码,但仍出现相同错误。

解决方法

报错核心原因是事件处理方法签名与TargetUpdated事件要求的委托不匹配,需按以下步骤修正:

  • 修正参数类型与命名空间
    确保后台代码引用System.Windows.Data命名空间,同时将参数的Object改为C#标准小写object:

    using System.Windows.Data;
    
  • 匹配标准委托签名
    TargetUpdated事件对应的委托是EventHandler<DataTransferEventArgs>,正确的方法签名应为:

    private void QuantityRequested_TargetUpdated(object sender, DataTransferEventArgs e)
    {
        // 自定义处理逻辑
    }
    

    (访问修饰符用private即可,XAML可正常绑定实例的私有事件处理方法)

  • 补充MultiBinding的NotifyOnTargetUpdated属性
    除了子Binding,MultiBinding本身也需要添加NotifyOnTargetUpdated="True",否则子Binding更新时可能无法触发TextBlock的TargetUpdated事件:

    <MultiBinding StringFormat="{}{0} Quantity {1} {2}" NotifyOnTargetUpdated="True">
        <!-- 子Binding内容 -->
    </MultiBinding>
    

内容的提问来源于stack exchange,提问作者Benilda Key

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 18:55:32