ストーリーボード x:Name へのアクセスが Silverlight では機能するのに、WPF では機能しないのはなぜですか?

StackOverflow https://stackoverflow.com/questions/681054

  •  22-08-2019
  •  | 
  •  

質問

次の WPF コードではエラーが発生します。 名前「zipButtonOut」は現在のコンテキストに存在しません。

ただし、ここで示すように、同じコードが Silverlight で動作します。 http://tanguay.info/web/index.php?pg=codeExamples&id=65

Window.Resources 内の Storyboard にアクセスできるようにするには、WPF コードに対して何をする必要がありますか? WPF UserControl でも試してみましたが、同じエラーが発生しました。

XAML:

<Window x:Class="TestDataGrid566.Test1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Test1" Height="300" Width="300">
    <Window.Resources>
        <Storyboard x:Name="zipButtonOut" x:Key="zipButtonOut">
            <DoubleAnimation Storyboard.TargetName="buttonContinue"
Storyboard.TargetProperty="Width"
From="0" To="300" Duration="0:0:.2"></DoubleAnimation>
            <DoubleAnimation Storyboard.TargetName="buttonContinue"
Storyboard.TargetProperty="Height"
From="2" To="50" Duration="0:0:.4"></DoubleAnimation>
        </Storyboard>
    </Window.Resources>

    <Grid x:Name="LayoutRoot" Background="White">
        <StackPanel HorizontalAlignment="Center" Margin="20">
            <Button x:Name="buttonBegin" Content="Click here to begin" Background="Green" Click="buttonBegin_Click"/>
            <Button x:Name="buttonContinue" Margin="0 70 0 0" Width="160" Height="2" FontSize="18" Background="Yellow"
Content="Click here to continue" Visibility="Collapsed"></Button>
        </StackPanel>
    </Grid>
</Window>

コードビハインド:

using System.Windows;

namespace TestDataGrid566
{
    public partial class Test1 : Window
    {
        public Test1()
        {
            InitializeComponent();
        }

        private void buttonBegin_Click(object sender, RoutedEventArgs e)
        {
            buttonBegin.Visibility = Visibility.Collapsed;
            buttonContinue.Visibility = Visibility.Visible;
            //zipButtonOut.Begin(); //GETS ERROR: The name 'zipButtonOut' does not exist in the current context.
        }
    }
}
役に立ちましたか?

解決

Silverlight で機能する理由はわかりませんが、WPF では、リソース コレクションに追加したコントロールは、背後のコード内の x:Name では使用できません。これらは、x:Key によって Resources コレクションを通じてアクセスできるため、x:Name 属性を削除し、背後のコード内のコメント化された行の直前に次のコード行を追加すると、機能します (コメントを解除します)。もちろん問題の行です):

Storyboard zipButtonOut = (Storyboard)Resources["zipButtonOut"];

これには次の using ステートメントが必要であることに注意してください。

using System.Windows.Media.Animation;

他のヒント

VS Silverlight ツールは、x:Name リソースに対しても「zipButtonOut」アクセサーを生成するようです。今後は、obj フォルダー内の生成されたファイル (おそらく「test1.g.cs」) を見て、x:Names に対してどのようなコードが生成されるかを確認してください。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top