将颜色绑定到UserControl中的DependencyProperty

时间:2019-03-04 03:16:48

标签: wpf colors

我有一个UserControl,它的一个Grid具有绑定的Background属性。我所有其他绑定都按预期工作,但是由于某种原因,我在UserControl中获得的唯一颜色是为DependencyProperty设置的默认值。

引用UserControl中的MainWindow.xaml

<controls:MyUserControl Title="{Binding Path=MyObjects[0].Title" MyControlColor="{Binding Path=MyObjects[0].Color}" />

Title会按预期显示,但颜色不变。

MyUserControl代码(我将MyControlColorBrush用于颜色源,它仅将MyControlColor转换为SolidColorBrush。代码向下。):

<Grid Background="{Binding Path=MyControlColorBrush, RelativeSource={RelativeSource AncestorType=UserControl}}">
    <TextBlock Text="{Binding Path=Title, RelativeSource={RelativeSource AncestorType=UserControl}}" />
</Grid>

MyUserControl.xaml.cs代码:

public Color MyControlColor
{
    get { return (Color)GetValue(MyControlColorProperty); }
    set { SetValue(MyControlColorProperty, value); }
}
    public static readonly DependencyProperty MyControlColorProperty = DependencyProperty.Register("MyControlColor", typeof(Color), typeof(MyUserControl), new PropertyMetadata(Colors.Black));

然后是一个仅将颜色转换为SolidColorBrush的属性:

public SolidColorBrush MyControlColorBrush
{
    get { return new SolidColorBrush(MyControlColor); }
}

关于我可能会丢失的任何想法?如果我检查MyControlColor的值,则显示正确的颜色,但是Grid的背景并未从Black改变。

1 个答案:

答案 0 :(得分:0)

与MyControlColorBrush的绑定仅在首次加载页面时发生一次。您与MyObjects[0].Color的绑定导致您的依赖项属性更新,但是没有任何迹象表明您的应用程序的其余部分也需要更新MyControlColorBrush。

有几种方法可以实现此目的,最简单的方法可能是为您的画笔创建一个只读的依赖属性,该属性在您检测到颜色属性发生变化时就进行更新(这类似于Width / ActualWidth的方式属性工作)。您的控件将需要DP来显示颜色:

public Color MyControlColor
{
    get { return (Color)GetValue(MyControlColorProperty); }
    set { SetValue(MyControlColorProperty, value); }
}

public static readonly DependencyProperty MyControlColorProperty =
    DependencyProperty.Register("MyControlColor", typeof(Color), typeof(MyUserControl),
        new PropertyMetadata(Colors.Black, OnColorChanged));

然后是画笔的只读DP:

public Brush MyControlColorBrush
{
    get { return (Brush)GetValue(MyControlColorBrushProperty); }
    protected set { SetValue(MyControlColorBrushPropertyKey, value); }
}

private static readonly DependencyPropertyKey MyControlColorBrushPropertyKey
        = DependencyProperty.RegisterReadOnly("MyControlColorBrush", typeof(Brush), typeof(MyUserControl),
                new FrameworkPropertyMetadata(Brushes.Black, FrameworkPropertyMetadataOptions.None));

public static readonly DependencyProperty MyControlColorBrushProperty = MyControlColorBrushPropertyKey.DependencyProperty;

每当颜色DP变化时,您都将更新画笔:

private static void OnColorChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    (d as MyUserControl).MyControlColorBrush = new SolidColorBrush((Color)e.NewValue);
}

自定义控件中的GUI元素然后绑定到只读DP,例如:

<Grid Background="{Binding Path=MyControlColorBrush, RelativeSource={RelativeSource AncestorType=local:MyUserControl}}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />