自定义WPF控件绑定ViewModel时属性无法生效的问题排查
搞定你的WPF自定义控件绑定问题
嘿,我一眼就看出问题出在哪了——你在自定义DynamicMenu的XAML里硬设置了DataContext="{Binding RelativeSource={RelativeSource Self}}",这直接把控件内部的上下文锁死在自身上了!
为啥会这样?
当你在外部用<local:DynamicMenu Text="{Binding Test}"/>时,这个{Binding Test}本来应该找外部ViewModel里的Test属性,但因为控件内部把DataContext改成了自己,绑定引擎会去DynamicMenu控件里找Test属性——可你根本没定义这个属性啊!所以绑定失败,就显示依赖属性的默认值"Empty"了。而静态值Text="test"是直接给依赖属性赋值,不受DataContext影响,所以能正常显示。
解决方案来了,两种方法任你选:
方法1:移除内部DataContext,用RelativeSource绑定内部控件
把UserControl的XAML里的DataContext设置删掉,然后让内部的TextBlock通过RelativeSource找到父级的UserControl来绑定Text属性:
<UserControl x:Class="Whelen.Griffin.Views.DynamicMenu" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300"> <!-- 删掉了DataContext的硬编码 --> <TextBlock Text="{Binding Text, RelativeSource={RelativeSource AncestorType=UserControl}}"/> </UserControl>
方法2:给控件起个名字,用ElementName绑定
如果觉得RelativeSource写起来啰嗦,给UserControl加个名字,内部绑定直接用ElementName指向它:
<UserControl x:Class="Whelen.Griffin.Views.DynamicMenu" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" x:Name="ThisMenu" d:DesignHeight="300" d:DesignWidth="300"> <TextBlock Text="{Binding Text, ElementName=ThisMenu}"/> </UserControl>
额外说一句
你的依赖属性定义完全没问题,FrameworkPropertyMetadataOptions.BindsTwoWayByDefault的设置很到位,不需要改它。
内容的提问来源于stack exchange,提问作者Chris Chevalier
相关产品推荐
相关产品推荐

