لماذا يعمل الوصول إلى Storyboard x:Name الخاص بي في Silverlight ولكن ليس في WPF؟
-
22-08-2019 - |
سؤال
يحصل رمز WPF التالي على الخطأ: الاسم "zipButtonOut" غير موجود في السياق الحالي.
ومع ذلك، يعمل الرمز المطابق في Silverlight كما أوضح هنا: http://tanguay.info/web/index.php?pg=codeExamples&id=65
ما الذي يجب علي فعله برمز WPF حتى أتمكن من الوصول إلى Storyboard داخل Window.Resources؟ لقد جربته أيضًا في 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، لذا يمكنك إزالة السمة x:Name وإضافة السطر التالي من التعليمات البرمجية مباشرةً قبل التعليق على السطر الموجود في التعليمات البرمجية خلف ذلك، وسيعمل (أزل التعليق السطر المعني بالطبع):
Storyboard zipButtonOut = (Storyboard)Resources["zipButtonOut"];
لاحظ أن هذا يتطلب عبارة الاستخدام التالية:
using System.Windows.Media.Animation;
نصائح أخرى
يبدو أن أدوات VS Silverlight تنشئ موصل "zipButtonOut" لموارد x:Name أيضًا.في المستقبل، ما عليك سوى إلقاء نظرة على الملف الذي تم إنشاؤه (ربما "test1.g.cs") في مجلد obj لمعرفة الكود الذي تم إنشاؤه لـ x:Names.