I'm getting this warning in Visual Studio output window when binding on a SolidColorBrush property inside a DataTemplate:
System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=MyColor; DataItem=null; target element is 'SolidColorBrush' (HashCode=22943289); target property is 'Color' (type 'Color')
If I bind directly on the rectangle element, outside the DataTemplate, it all works well.
Can anyone explain why this difference in the two apparently similar usages from the sample code below:
My View:
<UserControl.Resources>
<vm:TestViewModel x:Key="_myTestVM"/>
<DataTemplate x:Key="testVMDataTemplate">
<Grid>
<Rectangle Height="30" Width="200" Margin="5">
<Rectangle.Fill>
<SolidColorBrush Color="{Binding Path=MyColor}" />
</Rectangle.Fill>
</Rectangle>
</Grid>
</DataTemplate>
</UserControl.Resources>
<Grid>
<StackPanel DataContext="{StaticResource _myTestVM}">
<!-- Binding *outside* the DataTemplate = works fine -->
<Rectangle Height="30" Width="200" Margin="5">
<Rectangle.Fill>
<SolidColorBrush Color="{Binding Path=MyColor}"/>
</Rectangle.Fill>
</Rectangle>
<!-- Binding *inside* the DataTemplate = output warning -->
<ContentControl Content="{Binding}" ContentTemplate="{StaticResource testVMDataTemplate}"/>
</StackPanel>
</Grid>
My ViewModel (TestViewModel):
public class TestViewModel {
private Color _color = Colors.Green;
public Color MyColor {
get { return _color; }
}
public TestViewModel() {
}
}
Update:
It evidently has to do with binding the Color property for the SolidColorBrush. The same thing is happening if I bind the Angle property on a RotateTransform object.
Thanks in advance.
Binding with default data source as DataContext
wont work for SolidColorBrush
type as they are not framework elements. Plus they are freezable and you are not allowed to change their colors dynamically through data context based color binding.
Either you will have to bind the color to the background fill via a converter that converts the color into a solid color brush.
<TextBlock Background="{Binding MyColor,
Converter={StaticResource ColorToBrushConverter}}" />
Or use Color as DynamicResource
and refer that in Solid Color Brush.
ControlTemplate Storyboard color animation problem
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With