我创建了一个简单的UserControl,其中包含一个
但是出于某些原因,当我尝试使用绑定时它却不起作用:
我的用户控件的
Value
属性:public partial class Label : UserControl
{
public Label()
{
InitializeComponent();
DataContext = this;
}
public object Value
{
get { return GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(object), typeof(Label), new PropertyMetadata(""));
}
我正在使用以下这段XAML代码:
<Border BorderBrush="#A0A0A0" BorderThickness="1, 1, 0, 0" CornerRadius="1">
<Border BorderBrush="#000000" BorderThickness="0, 0, 1, 1" CornerRadius="1">
<Border.Background>
<LinearGradientBrush StartPoint="0.5, 0" EndPoint="0.5, 1">
<GradientStop Color="#FFFFFF" Offset="0.0" />
<GradientStop Color="#E0E0E0" Offset="1.0" />
</LinearGradientBrush>
</Border.Background>
<TextBlock Width="100" FontWeight="SemiBold" Padding="2" Text="{Binding Value}" />
</Border>
</Border>
当我像这样明确设置值时,这个方法有效:
<uc:Label Value="Name" />
但是出于某些原因,当我尝试使用绑定时它却不起作用:
<ItemsControl ItemsSource="{Binding InfoDetran}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel>
<!-- Doesn't work -->
<uc:Label Value="{Binding Label}" />
<!-- But this works -->
<TextBox Text="{Binding Label}" />
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
我的用户控件的
Value
属性没有被更新,我得到了一个绑定错误:BindingExpression path error: 'Label' property not found on 'object' ''Label' (Name='')'. BindingExpression:Path=Label; DataItem='Label' (Name=''); target element is 'Label' (Name=''); target property is 'Value' (type 'Object')
这个object
是在寻找它上面的属性,我做错了什么?