[WPF] ToolTip用ElementName绑定无效 & x:Reference循环引用报错

ToolTip用ElementName绑定无效

问题详情:给控件元素的ToolTip属性使用ElementName进行绑定,源是一个INotifyPropertyChanged的属性Info,用来显示内容时,运行时不起效果(指没有改变内容,或者内容为空)。代码如下:
原因:Window是一棵逻辑树,ToolTip是另一棵逻辑树。
Label控件Content属性的ElementName绑定所引用的"MainWindow",它只会在ToolTip的逻辑树中搜索,但是无法访问到Window逻辑树。因此,在运行时,自然就无法得到Info的值。
1 <Window x:Name="MainWindow">
2 <Label>
3   <Label.ToolTip>
4     <Label Content="{Binding ElementName=MainWindow, Path=Info, Mode=OneWay}"/>
5   </Label.ToolTip>
6 </Label>

原理:x:Reference不使用运行时的逻辑树搜索,是在XAML文件生成元素的时候进行操作。
1 <Window x:Name="MainWindow">
2 <Label>
3   <Label.ToolTip>
4     <Label Content="{Binding Source={x:Reference Name=MainWindow}, Path=Info, Mode=OneWay}"/>
5   </Label.ToolTip>
6 </Label>

参考:https://blog.csdn.net/htxhtx123/article/details/104529659

如果你这样就已经完美解决了问题,那么就不用往下看了。


 


x:Reference循环引用报错

如果你在使用x:Reference进行绑定,并运行时,产生了解析XAML错误异常,提示为循环引用,并且指向我上文给出的解决方案,那么这就是下一个要解决的问题了。
问题详情:使用x:Reference对ToolTip进行绑定时,Visual Studio调试时发生XAML循环引用错误。
原因:有一些人在使用上文的方法后完美运行,大部分人都会报错,我猜测是新、旧版本对于XAML解析方式的不同。
1 <Window x:Name="MainWindow">
2 <Label>
3   <Label.ToolTip>
4     <Label Content="{Binding ElementName=MainWindow, Path=Info, Mode=OneWay}"/>
5   </Label.ToolTip>
6 </Label>

解决方案:创建一个Resources,类型为DiscreteObjectKeyFrame,Key为MainWindowProxy,绑定到MainWindow,然后用StaticResource将MainWindowProxy绑定给ToolTip,并用Value.Info访问源属性。代码如下:

虽然这是一个绕弯路的方法,但是实际写起来还是很优美的。

1 <Window x:Name="MainWindow">
2   <Window.Resources>
3       <DiscreteObjectKeyFrame x:Key="MainWindowProxy" Value="{Binding ElementName=MainWinow}" />
4   </Window.Resources>
5 <Label>
6   <Label.ToolTip>
7     <Label Content="{Binding Value.Info, Source={StaticResource MainWinowProxy}, Mode=OneWay}"/>
8   </Label.ToolTip>
9 </Label>

参考:https://stackoverflow.com/questions/32878883/wpf-databinding-error-in-tag-property

By https://www.cnblogs.com/liplum/p/ToolTip-Binding.html

posted @ 2020-10-08 17:42  普冷姆  阅读(453)  评论(0)    收藏  举报