我创建了一个简单的 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(""));
}
Run Code Online (Sandbox Code Playgroud)
我正在使用这个 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>
Run Code Online (Sandbox Code Playgroud)
当我像这样明确设置值时,这有效:
<uc:Label Value="Name" />
Run Code Online (Sandbox Code Playgroud)
但是由于某种原因,当我尝试使用绑定时它不会:
<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>
Run Code Online (Sandbox Code Playgroud)
Value我的 userControl的属性没有被更新,我收到了一个绑定错误: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它正在寻找的财产,我在做什么错?
在DataContext被从抹了你的手册二传手父继承。
您可以通过更改 XAML 将内容绑定DataContext到控件本身的内容来解决此问题,然后绑定将继续工作,因为继承的上下文始终是UserControl其自身:
<UserControl ...
x:Name="Root">
<Border DataContext="{Binding ElementName=Root}" 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>
</UserControl>
Run Code Online (Sandbox Code Playgroud)
注意我已经命名控件x:Name="Root"并将Border上下文绑定为DataContext="{Binding ElementName=Root}".
您可以DataContext = this从后面的代码中删除。