我有一个名为UserControl
的自定义ColorSelector
。在该控件的内部,我有两个DependencyProperties
设置如下:
public static readonly DependencyProperty SelectedColorProperty = DependencyProperty.Register("SelectedColor",
typeof(Color), typeof(ColorSelector), new PropertyMetadata(defaultColor, (o, e) => ((ColorSelector)o).propertyChangedColor()));
public static readonly DependencyProperty SelectedHexProperty = DependencyProperty.Register("SelectedHex",
typeof(string), typeof(ColorSelector), new PropertyMetadata("000000", (o, e) => ((ColorSelector)o).propertyChangedHex()));
public Color SelectedColor
{
get => (Color)GetValue(SelectedColorProperty);
set => SetValue(SelectedColorProperty, value);
}
public string SelectedHex
{
get => (string)GetValue(SelectedHexProperty);
set => SetValue(SelectedHexProperty, value);
}
但是,当我将UserControl
放置到另一个视图中时,在控制台中出现错误:
XAML:
<local:ColorSelector
Height="28"
Width="100"
SelectedColor="{Binding SelectionColor,
Mode=OneWay}"/>
控制台错误:(已重新格式化以方便阅读)
System.Windows.Data Error: 40 : BindingExpression path error: 'SelectionColor' property not found on 'object' ''ColorSelector' (Name='')'. BindingExpression:Path=SelectionColor; DataItem='ColorSelector' (Name=''); target element is 'ColorSelector' (Name=''); target property is 'SelectedColor' (type 'Color')
很明显ColorSelector
正在将自身用作DataContext。 (在我看来,我在标记中设置了DataContext,其他控件正在成功使用它)
此问题非常奇怪,因为该视图中的所有其他控件都已正确绑定,包括另一个用户控件 DependencyProperties
以相同的方式设置。 < / p>