【发布时间】:2011-01-16 08:01:53
【问题描述】:
我有一个 wpf 用户控件,它公开了一个自定义依赖属性。在用户控件内部,一个文本块绑定到 dp 的值。此数据绑定适用于所有场景,但数据源是对象时除外。
重现此所需的最少代码是:
这是用户控件的主要部分
<StackPanel Orientation="Horizontal">
<TextBlock Text="**SimpleUC** UCValue: "/>
<TextBlock Text="{Binding UCValue}"/>
</StackPanel>
以及后面的用户控制代码:
public SimpleUC()
{
InitializeComponent();
this.DataContext = this;
}
public string UCValue
{
get { return (string)GetValue(UCValueProperty); }
set { SetValue(UCValueProperty, value); }
}
public static readonly DependencyProperty UCValueProperty =
DependencyProperty.Register("UCValue", typeof(string), typeof(SimpleUC), new UIPropertyMetadata("value not set"));
这是测试窗口。我将我的项目 xml 命名空间导入为“自定义”
<Window.Resources>
<Style TargetType="{x:Type StackPanel}">
<Setter Property="Margin" Value="20"/>
</Style>
</Window.Resources>
<StackPanel>
<StackPanel>
<TextBlock Text="This fails to bind:"/>
<custom:SimpleUC UCValue="{Binding SomeData}"/>
</StackPanel>
<StackPanel>
<TextBlock>The same binding on a regular control like Label</TextBlock>
<Label Content="{Binding SomeData}"/>
</StackPanel>
<Slider x:Name="sld" />
<StackPanel>
<TextBlock>However, binding the UC to another element value, like a slider works</TextBlock>
<custom:SimpleUC UCValue="{Binding ElementName=sld,Path=Value}"/>
</StackPanel>
</StackPanel>
而后面的测试窗口代码是:
public TestWindow()
{
InitializeComponent();
this.DataContext = this;
}
//property to bind to
public string SomeData { get { return "Hello S.O."; } }
当我在 TestWindow 上打开诊断跟踪时,它会吐出错误“BindingExpression path error:
'SomeData' property not found on 'object' ''SimpleUC' (Name='')' ... "
绑定表达式与我在相邻标签中使用的相同,并且效果很好。这种行为对我来说真的很奇怪。有人能解释一下吗?
【问题讨论】:
标签: wpf data-binding user-controls