UWP后台代码中Style Setter的值绑定不生效该如何解决
问题原因
你直接将Binding实例赋值给ToolTipService.ToolTipProperty对应的Setter值时,WPF不会把这个实例当作需要执行的绑定逻辑,而是将它作为普通对象直接当作ToolTip的内容,最终显示的就是Binding对象调用ToString()后的文本,这就是你看到的异常效果。而赋值固定字符串时,WPF会直接把字符串作为ToolTip内容,所以显示正常。
解决方案
你需要显式创建ToolTip实例,将绑定应用到ToolTip的Content属性上,再把这个ToolTip实例赋值给Setter,修改你的Style部分代码即可:
CValueConverter valueConverter = new CValueConverter() { Field = fieldDg }; Style textStyle = new Style(typeof(TextBlock)); textStyle.Setters.Add(new Setter(TextBlock.TextTrimmingProperty, TextTrimming.CharacterEllipsis)); // 新增:创建ToolTip实例,给ToolTip的Content属性添加绑定 ToolTip toolTip = new ToolTip(); toolTip.SetBinding(ToolTip.ContentProperty, new Binding { // 绑定路径取ToolTip的宿主TextBlock的DataContext对应索引的值 Path = new PropertyPath($"PlacementTarget.DataContext[{cmnIndex}]"), RelativeSource = RelativeSource.Self, Converter = valueConverter }); // 把ToolTip实例赋值给Setter textStyle.Setters.Add(new Setter(ToolTipService.ToolTipProperty, toolTip)); this.FormListDg.Columns.Add(new DataGridTextColumn() { Header = fieldDg.Name, HeaderStyle = this.GetHeaderStyle(fieldDg.Color), CellStyle = this.GetCellStyle(fieldDg.Color), CanUserSort = true, MaxWidth = 300, Binding = new Binding { Path = new PropertyPath("[" + cmnIndex.ToString() + "]"), Converter = valueConverter }, ElementStyle = textStyle }); cmnIndex++;
内容的提问来源于stack exchange,提问作者Spuriga
相关产品推荐
相关产品推荐

