我在 WPF 中遇到数据绑定问题。
当我尝试使用值转换器并将 NotifyOnTargetUpdated=True 属性设置为 True 时,我收到带有以下消息的 XamlParseException:
“System.Windows.Data.BindingExpression”值不能分配给对象“View.UserControls.ShadowedText”的属性“Contenu”。值不能为空。参数名称:标记文件“View.UserControls;component/saletotal.xaml”第 363 行位置 95 中对象“System.Windows.Data.Binding”处的 textToFormat 错误。
绑定非常标准:
<my:ShadowedText Contenu="{Binding Path=Total,
Converter={StaticResource CurrencyToStringConverter},
NotifyOnTargetUpdated=True}"
TargetUpdated="MontantTotal_TargetUpdated">
</my:ShadowedText>
(为简洁起见删除了样式属性)
转换器存在于资源中,并在 NotifyOnTargetUpdated=True 被移除时正常工作。同样,正确调用和实现 TargetUpdated 事件,并在删除转换器时工作。
注意:此绑定是在 ControlTemplate 中定义的,尽管我认为这与问题无关。
谁能解释我发生了什么?我定义绑定错误吗?这些功能是否相互排斥(在这种情况下,您能解释一下为什么会这样)吗?
提前致谢。
更多信息:这是 TargetUpdated 处理程序的内容:
private void MontantTotal_TargetUpdated(object sender, DataTransferEventArgs e)
{
ShadowedText textBlock = (ShadowedText)e.TargetObject;
double textSize = textBlock.Taille;
double delta = 5;
double defaultTaille = 56;
double maxWidth = textBlock.MaxWidth;
while (true)
{
FormattedText newFormat = new FormattedText(textBlock.Contenu,
CultureInfo.CurrentCulture, FlowDirection.LeftToRight,
new Typeface("Calibri"), textSize,
(SolidColorBrush) Resources["RougeVif"]);
if (newFormat.Width < textBlock.MaxWidth && textSize <= defaultTaille)
{
if ((Math.Round(newFormat.Width) + delta) >= maxWidth || textSize == defaultTaille)
{
break;
}
textSize++;
}
else
{
if ((Math.Round(newFormat.Width) - delta) <= maxWidth && textSize <= defaultTaille)
{
break;
}
textSize--;
}
}
textBlock.Taille = textSize;
}
处理程序的作用是根据内容的长度调整控件的大小。这很丑陋,但我想让功能部分在重构之前工作。