'Cannot find governing FrameworkElement…' warning when binding inside DataTemplates

空扰寡人 提交于 2019-11-28 02:48:08

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/7926204/cannot-find-governing-frameworkelement-warning-when-binding-inside-datatemp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!