我有一个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
改变。
答案 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" />