Search code examples
wpfdata-bindingwpf-controls

binding in datatemplate cause an error 'Cannot find governing FrameworkElement or FrameworkContentElement for target element'


  1. When both place1(TextBlock in mainwindow) and place2(MergedDictionaries in app.xaml) exist, cause an error:'Cannot find governing FrameworkElement or FrameworkContentElement for target element'
  2. When one or both of place1 and place2 are commented out, the error is not displayed
  3. so why?

source is here

MainWindow.cs

<Window x:Class="Demo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Demo"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <StackPanel>
        <!--place1-->
        <TextBlock>Hello</TextBlock>
        <Button Content="Foo">
            <Button.ContentTemplate>
                <DataTemplate>
                    <StackPanel>
                        <TextBlock x:Name="Bar">Hello</TextBlock>
                        <TextBlock Text="{Binding}">
                            <TextBlock.RenderTransform>
                                <!--error position-->
                                <RotateTransform Angle="{Binding ElementName=Bar,Path=ActualHeight}"/>
                            </TextBlock.RenderTransform>
                        </TextBlock>
                    </StackPanel>
                </DataTemplate>
            </Button.ContentTemplate>
        </Button>
    </StackPanel>
</Window>

App.Xaml

<Application x:Class="Demo.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:Demo"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <!--place2-->
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="pack://application:,,,/Demo.Lib;component/Themes/Generic.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

Solution

  • I solved my issue by not merging as @BionicCode say 'it is not necessary to merge the Generic.xaml into the App.xaml'