在'System.Windows.Controls.Button'的名称范围中找不到名称

时间:2014-12-31 00:29:39

标签: c# wpf storyboard

我的Template

有以下Button
<Window.Resources>
    <DataTemplate x:Key="ItemTemplate">
        <DockPanel Width="Auto">
            <Button DockPanel.Dock="Top">                                           
                <Button.Template>
                    <ControlTemplate >
                        <Image  Source="{Binding image}"/>
                    </ControlTemplate>
                </Button.Template>                    
                <Button.Triggers>
                    <EventTrigger RoutedEvent="Button.Click">
                        <BeginStoryboard>
                            <Storyboard>
                                <local:GridLengthAnimation
                                    Storyboard.TargetName="col1"
                                    Storyboard.TargetProperty="Width"
                                    LeftGridWidth="*" RightGridWidth="1*" Duration="0:0:2"/>
                            </Storyboard>
                        </BeginStoryboard>
                    </EventTrigger>
                </Button.Triggers>
            </Button>
        </DockPanel>
    </DataTemplate>
</Window.Resources>

<Grid>
     ...
     ...
     <Grid Grid.Row="2" >

        <Grid.ColumnDefinitions>
            <ColumnDefinition Name="col1" Width="{Binding ElementName=root, Path=DataContext.gla.LeftGridWidth}" />
            <ColumnDefinition Name="col2" Width="{Binding ElementName=root, Path=DataContext.gla.RightGridWidth}" />
        </Grid.ColumnDefinitions>

        <Grid x:Name="LeftGrid" Grid.Row="2" Grid.Column="0" >
              <Border BorderThickness="1" BorderBrush="Red">
                  <ItemsControl ItemTemplate="{StaticResource ItemTemplate}" ItemsSource="{Binding ElementName=root, Path=DataContext._movies}">
                      <ItemsControl.ItemsPanel>
                          <ItemsPanelTemplate>
                              <UniformGrid Columns="5"/>
                          </ItemsPanelTemplate>
                      </ItemsControl.ItemsPanel>
                  </ItemsControl>
              </Border>
        </Grid>
     </Grid>
</Grid>

问题是col1未提及Storyboard.TargetName="col1"。我收到错误:

An unhandled exception of type 'System.InvalidOperationException' occurred in PresentationFramework.dll

Additional information: 'col1' name cannot be found in the name scope of 'System.Windows.Controls.Button'.

我认为这可能与我使用Items Control的事实有关......我认为col1会在任何包含元素中被发现。我不确定如何解决这个问题。

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:17)

问题确实是由ItemsControl引起的,Button使其Storyboard.TargetName及其资源处于不同的范围。

一个简单的解决方法是,而不是使用Storyboard.Target,而是使用Storyboard.Target="{Binding ElementName=col1}" 绑定,而不是像这样 -

{{1}}

答案 1 :(得分:0)

尝试在

中使用x:Name而不是Name
<ColumnDefinition Name="col1" Width="{Binding ElementName=root, Path=DataContext.gla.LeftGridWidth}" />