`
收藏列表
标题 标签 来源
Android ImageUtil android
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Bitmap.Config;
import android.graphics.PorterDuff.Mode;
import android.graphics.drawable.Drawable;

public class BitmapUtil
{
    public static Bitmap getRoundedCornerBitmap(Bitmap bmpSrc, float rx, float ry)
    {
        if (null == bmpSrc)
        {
            return null;
        }

        int bmpSrcWidth = bmpSrc.getWidth();
        int bmpSrcHeight = bmpSrc.getHeight();

        Bitmap bmpDest = Bitmap.createBitmap(bmpSrcWidth, bmpSrcHeight, Config.ARGB_8888);
        if (null != bmpDest)
        {
            Canvas canvas = new Canvas(bmpDest);
            final int color = 0xff424242;
            final Paint paint = new Paint();
            final Rect rect = new Rect(0, 0, bmpSrcWidth, bmpSrcHeight);
            final RectF rectF = new RectF(rect);

            // Setting or clearing the ANTI_ALIAS_FLAG bit AntiAliasing smooth out
            // the edges of what is being drawn, but is has no impact on the interior of the shape.
            paint.setAntiAlias(true);

            canvas.drawARGB(0, 0, 0, 0);
            paint.setColor(color);
            canvas.drawRoundRect(rectF, rx, ry, paint);
            paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
            canvas.drawBitmap(bmpSrc, rect, rect, paint);
        }

        return bmpDest;
    }

    public static Bitmap duplicateBitmap(Bitmap bmpSrc)
    {
        if (null == bmpSrc)
        {
            return null;
        }
        
        int bmpSrcWidth = bmpSrc.getWidth();
        int bmpSrcHeight = bmpSrc.getHeight();

        Bitmap bmpDest = Bitmap.createBitmap(bmpSrcWidth, bmpSrcHeight, Config.ARGB_8888);
        if (null != bmpDest)
        {
            Canvas canvas = new Canvas(bmpDest);
            final Rect rect = new Rect(0, 0, bmpSrcWidth, bmpSrcHeight);
            
            canvas.drawBitmap(bmpSrc, rect, rect, null);
        }
        
        return bmpDest;
    }
    
    public static Bitmap getScaleBitmap(Bitmap bitmap, float wScale, float hScale)
    {
        Matrix matrix = new Matrix();
        matrix.postScale(wScale, hScale);
        Bitmap bmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        
        return bmp;
    }
    
    public static Bitmap getSizedBitmap(Bitmap bitmap, int dstWidth, int dstHeight)
    {
        if (null != bitmap)
        {
            Bitmap result = Bitmap.createScaledBitmap(bitmap, dstWidth, dstHeight, false);
            return result;
        }
        
        return null;
    }
    
    public static Bitmap getFullScreenBitmap(Bitmap bitmap, int wScale, int hScale)
    {
        int dstWidth = bitmap.getWidth() * wScale;
        int dstHeight = bitmap.getHeight() * hScale;
        Bitmap result = Bitmap.createScaledBitmap(bitmap, dstWidth, dstHeight, false);
        return result;
    }

    public static Bitmap byteArrayToBitmap(byte[] array)
    {
        if (null == array)
        {
            return null;
        }
        
        return BitmapFactory.decodeByteArray(array, 0, array.length);
    }

    public static byte[] bitampToByteArray(Bitmap bitmap)
    {
        byte[] array = null;
        try 
        {
            if (null != bitmap)
            {
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
                array = os.toByteArray();
                os.close();
            }
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }
        
        return array;
    }

    public static void saveBitmapToFile(Context context, Bitmap bmp, String name)
    {
        if (null != context && null != bmp && null != name && name.length() > 0)
        {
            try
            {
                FileOutputStream fos = context.openFileOutput(name, Context.MODE_WORLD_WRITEABLE);
                bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
                fos.flush();
                fos.close();
                fos = null;
            }
            catch(IOException e)
            {
                e.printStackTrace();
            }
        }
    }

    public static Bitmap loadBitmapFromFile(Context context, String name)
    {
        Bitmap bmp = null;

        try
        {
            if (null != context && null != name && name.length() > 0)
            {
                FileInputStream fis = context.openFileInput(name);
                bmp = BitmapFactory.decodeStream(fis);
                fis.close();
                fis = null;
            }
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }

        return bmp;
    }

    public static Bitmap drawableToBitmap(Drawable drawable)
    {
        if (null == drawable)
        {
            return null;
        }
        
        int width = drawable.getIntrinsicWidth();
        int height = drawable.getIntrinsicHeight();
        Config config = (drawable.getOpacity() != PixelFormat.OPAQUE) ? Config.ARGB_8888 : Config.RGB_565;
        
        Bitmap bitmap = Bitmap.createBitmap(width, height, config);
        
        if (null != bitmap)
        {
            Canvas canvas = new Canvas(bitmap);
            drawable.setBounds(0, 0, width, height);
            drawable.draw(canvas);
        }
        
        return bitmap;
    }
    
    public static void saveBitmapToSDCard(Bitmap bmp, String strPath)
    {
        if (null != bmp && null != strPath && !strPath.equalsIgnoreCase(""))
        {
            try
            {
                File file = new File(strPath);
                FileOutputStream fos = new FileOutputStream(file);
                byte[] buffer = BitmapUtil.bitampToByteArray(bmp);
                fos.write(buffer);
                fos.close();
            }
            catch (FileNotFoundException e)
            {
                e.printStackTrace();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }

    public static Bitmap loadBitmapFromSDCard(String strPath)
    {
        File file = new File(strPath);

        try
        {
            FileInputStream fis = new FileInputStream(file);            
            Bitmap bmp = BitmapFactory.decodeStream(fis);
            return bmp;
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        
        return null;
    }
}
Textbox在没有内容时背景显示提示
<TextBox Width="400" Height="50">
            <TextBox.Resources>
                <VisualBrush x:Key="HelpBrush" TileMode="None" Opacity="0.3" Stretch="None" AlignmentX="Left">
                    <VisualBrush.Visual>
                        <TextBlock FontStyle="Italic" Text="请输入用户名"/>
                    </VisualBrush.Visual>
                </VisualBrush>
            </TextBox.Resources>
            <TextBox.Style>
                <Style TargetType="TextBox">
                    <Style.Triggers>
                        <Trigger Property="Text" Value="{x:Null}">
                           <Setter Property="Background" Value="{StaticResource HelpBrush}"/>
                            <!-- <Setter Property="Background" >
                                <Setter.Value>
                                    <VisualBrush>
                                        <VisualBrush.Visual>
                                        <TextBlock FontStyle="Italic" Text="请输入用户名"/>
                                            </VisualBrush.Visual>
                                    </VisualBrush>
                                </Setter.Value>
                            </Setter>-->
                        </Trigger>
                        <Trigger Property="Text" Value="">
                            <Setter Property="Background" Value="{StaticResource HelpBrush}"/>
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </TextBox.Style>          
        </TextBox>
XmlSerializer序列化和反序列化 windows 8, metro
//将AppSettings类保存成xml,XmlSerializer的限制是只能序列化public的Property,若不想序列化某个Property,则用[XmlIgnore]特性标出。还有其他的特性,参阅文档
public async Task SaveAsync()
        {
            string settingsXml = null;

            using (StringWriter stringWriter = new StringWriter())
            {
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(AppSettings));
                xmlSerializer.Serialize(stringWriter, this);
                settingsXml = stringWriter.ToString();
            }
            StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
            StorageFile storageFile = null;

            try
            {
                storageFile = await storageFolder.CreateFileAsync(FILENAME,
                                                       CreationCollisionOption.ReplaceExisting);
            }
            catch (Exception)
            {
                // TODO: This shouldn't happen, but it might
            }
            await FileIO.WriteTextAsync(storageFile, settingsXml);
        }
//从文本文件中读取xml并放序列化生成该对象

 public async static Task<AppSettings> LoadAsync()
        {
            StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
            StorageFile appSettingsFile = null;
            AppSettings appSettings = null;

            try
            {
                appSettingsFile = await storageFolder.GetFileAsync(FILENAME);
            }
            catch (Exception)
            {
                // This happens the first time the program is run
            }

            if (appSettingsFile == null)
            {
                appSettings = new AppSettings();
            }
            else
            {
                string str = await FileIO.ReadTextAsync(appSettingsFile);
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(AppSettings));

                using (StringReader reader = new StringReader(str))
                {
                    appSettings = xmlSerializer.Deserialize(reader) as AppSettings;
                }
            }
            return appSettings;
        }
Metro Task whenAny 出现异常时的解决模型
foreach(Task recommendation in recommendations)
{
var ignored = recommendation.ContinueWith(
t => { if (t.IsFaulted) Log(t.Exception); });
}

or
foreach(Task recommendation in recommendations)
{
var ignored = recommendation.ContinueWith(
t => Log(t.Exception), TaskContinuationOptions.OnlyOnFaulted);
}

其中,ContnueWith为,当Task完成时(可能是失败或成功),要做的事情。
Metro Task waitAll
Task [] asyncOps = (from addr in addrs selectSendMailAsync(addr)).ToArray();
try
{
awaitTask.WhenAll(asyncOps);
}
catch(Exception exc)
{
foreach(Task faulted in asyncOps.Where(t => t.IsFaulted))
    {
        … // work with faulted and faulted.Exception
    }
}
Metro Task的Cache模式使用
publicTask<int>GetValueAsync(string key)
{
int cachedValue;
return TryGetCachedValue(out cachedValue) ?
Task.FromResult(cachedValue) :
GetValueAsyncInternal();
}

privateasyncTask<int>GetValueAsyncInternal(string key)
{
    …
}

其中Task.FromResult(T)将构造一个已经完成状态的Task,这样上一层的Metho将可以同步的执行。
Metro 构建上层可控制,可触发的Task
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;

class TCSDemo
{
    //可以将老的回调方式的api改成最新移步模式
    // Demonstrated features:
    // 		TaskCompletionSource ctor()
    // 		TaskCompletionSource.SetResult()
    // 		TaskCompletionSource.SetException()
    //		Task.Result
    // Expected results:
    // 		The attempt to get t1.Result blocks for ~1000ms until tcs1 gets signaled. 15 is printed out.
    // 		The attempt to get t2.Result blocks for ~1000ms until tcs2 gets signaled. An exception is printed out.
    // Documentation:
    //		http://msdn.microsoft.com/en-us/library/dd449199(VS.100).aspx
    static void Main()
    {
        TaskCompletionSource<int> tcs1 = new TaskCompletionSource<int>();
        Task<int> t1 = tcs1.Task;

        // Start a background task that will complete tcs1.Task
        Task.Factory.StartNew(() =>
        {
            Thread.Sleep(1000);
            tcs1.SetResult(15);
        });

        // The attempt to get the result of t1 blocks the current thread until the completion source gets signaled.
        // It should be a wait of ~1000 ms.
        Stopwatch sw = Stopwatch.StartNew();
        int result = t1.Result;
        sw.Stop();

        Console.WriteLine("(ElapsedTime={0}): t1.Result={1} (expected 15) ", sw.ElapsedMilliseconds, result);

        // ------------------------------------------------------------------

        // Alternatively, an exception can be manually set on a TaskCompletionSource.Task
        TaskCompletionSource<int> tcs2 = new TaskCompletionSource<int>();
        Task<int> t2 = tcs2.Task;

        // Start a background Task that will complete tcs2.Task with an exception
        Task.Factory.StartNew(() =>
        {
            Thread.Sleep(1000);
            tcs2.SetException(new InvalidOperationException("SIMULATED EXCEPTION"));
        });

        // The attempt to get the result of t2 blocks the current thread until the completion source gets signaled with either a result or an exception.
        // In either case it should be a wait of ~1000 ms.
        sw = Stopwatch.StartNew();
        try
        {
            result = t2.Result;

            Console.WriteLine("t2.Result succeeded. THIS WAS NOT EXPECTED.");
        }
        catch (AggregateException e)
        {
            Console.Write("(ElapsedTime={0}): ", sw.ElapsedMilliseconds);
            Console.WriteLine("The following exceptions have been thrown by t2.Result: (THIS WAS EXPECTED)");
            for (int j = 0; j < e.InnerExceptions.Count; j++)
            {
                Console.WriteLine("\n-------------------------------------------------\n{0}", e.InnerExceptions[j].ToString());
            }
        }
    }

}
Metro 报文套接字
client :
 DatagramSocket socket = new DatagramSocket();
            await socket.ConnectAsync(new HostName("localhost"), "858586");
            //IOutputStream io = await socket.GetOutputStreamAsync();
            DataWriter writer = new DataWriter(socket.OutputStream);
            writer.UnicodeEncoding = UnicodeEncoding.Utf8;
            writer.WriteString("success");
            await writer.StoreAsync();
          bool b=  await writer.FlushAsync();
            writer.Dispose();
            socket.Dispose();

Server:
            socket = new DatagramSocket();
            socket.MessageReceived += socket_MessageReceived;//先设置接收,然后再绑定
            await socket.BindEndpointAsync(new HostName("localhost"), "858586");

 void socket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
        {
            string text = args.GetDataReader().ReadString(7);
            sender.Dispose();
        }
将C#中的Task转换包装成WinRT组建接口导出
  public sealed class AsyncMethods
    {
            public IAsyncOperation<string> Get(string url)
            {
                // this is Key.  It converts an async task into IAsyncOperation:
                return (IAsyncOperation<string>)AsyncInfo.Run(await(System.Threading.CancellationToken ct) => GetInternal(url));
            }
            private static async Task<string> GetInternal(string url)
            {
                var client = new HttpClient();
                var response = await client.GetAsync(url);
                return response.Content.ReadAsString();
            }
        }
Metro 两个App相关的目录
Windows.ApplicationModel.Package.Current.InstalledLocation  安装目录,一般是安装目录(exe)所在的APPX文件夹 。在URL中表示的前缀是:"ms-appx:///"
Windows.Storage.ApplicationData.Current.LocalFolder.Path Windows为每个应用分配的数据存放目录,是一个隐藏文件,/Users/[username]/AppData/Local/Packages/[package family name]/LocalState。在URL中表示方式的前缀是:"ms-appdata:///local/"
正则表达式
search num
MatchCollection mathcs=  Regex.Matches(source,@"\d*");
          foreach (Match item in mathcs)
          {
              if (item.Value.Trim().Equals(""))
              {
                  continue;
              }
              int i = int.Parse(item.Value);
          }
帧动画Metro
  <StackPanel>
            <StackPanel.Resources>
                <Storyboard x:Name="myStoryboard">
                    <!--<DoubleAnimation
                        EnableDependentAnimation="True"
                        
          Storyboard.TargetName="translate"
          Storyboard.TargetProperty="X"
           To="0" Duration="0:0:3"
          AutoReverse="True" RepeatBehavior="Forever" />-->
                    <!--<ObjectAnimationUsingKeyFrames>
                        
                    </ObjectAnimationUsingKeyFrames>-->
                    <DoubleAnimationUsingKeyFrames EnableDependentAnimation="True"
                    Storyboard.TargetName="translate"
                      Storyboard.TargetProperty="X" Duration="0:0:5">
                        <LinearDoubleKeyFrame Value="-300" KeyTime="0:0:1"/>
                        <LinearDoubleKeyFrame Value="-250" KeyTime="0:0:1.5"/>
                        <LinearDoubleKeyFrame Value="-200" KeyTime="0:0:2"/>
                        <LinearDoubleKeyFrame Value="-100" KeyTime="0:0:3"/>
                        <LinearDoubleKeyFrame Value="0" KeyTime="0:0:4"/>
                        <LinearDoubleKeyFrame Value="-50" KeyTime="0:0:5"/>
                    </DoubleAnimationUsingKeyFrames>
                </Storyboard>
            </StackPanel.Resources>

            <Button Click="Start_Animation" x:Name="MyAnimatedRectangle"
            
     Width="400" Height="100" Background="Blue" >
                <Button.RenderTransform>
                    <TranslateTransform x:Name="translate" X="-350" Y="0"/>
                </Button.RenderTransform>
            </Button>
metro 动画实现之作用于一个TranslateTransform
 <StackPanel>
            <StackPanel.Resources>
                <Storyboard x:Name="myStoryboard">
                    <DoubleAnimation
                        EnableDependentAnimation="True"
          Storyboard.TargetName="translate"
          Storyboard.TargetProperty="X"
           To="0" Duration="0:0:3"
          AutoReverse="True" RepeatBehavior="Forever" />
                    <!--<ObjectAnimationUsingKeyFrames>
                        
                    </ObjectAnimationUsingKeyFrames>-->
                </Storyboard>
            </StackPanel.Resources>

            <Button Loaded="Start_Animation" x:Name="MyAnimatedRectangle"
            
     Width="300" Height="100" Background="Blue" >
                <Button.RenderTransform>
                    <TranslateTransform x:Name="translate" X="-300" Y="0"/>
                </Button.RenderTransform>
            </Button>

        </StackPanel>
 private void Start_Animation(object sender, RoutedEventArgs e)
        {
            myStoryboard.Begin();
        }   
Metro 共享接收保存的图片
 IRandomAccessStreamReference imageReceived = await this.shareOperation.Data.GetBitmapAsync();
                    IRandomAccessStreamWithContentType stream = await imageReceived.OpenReadAsync();
                    StorageFile file = await Windows.ApplicationModel.Package.Current.InstalledLocation.CreateFileAsync("pic.jpg",CreationCollisionOption.ReplaceExisting);
                    DataReader dr = new DataReader(stream);
                    uint count = await dr.LoadAsync((uint)stream.Size);
                    Byte[] bytes = new Byte[(int)count];
                    dr.ReadBytes(bytes);
                    DataWriter dw = new DataWriter(await file.OpenAsync(FileAccessMode.ReadWrite));                                       
                    dw.WriteBytes(bytes);
                    await dw.StoreAsync();
                    await dw.FlushAsync();
                    dw.Dispose();
                    dr.Dispose();
                    stream.Dispose();
读取文件为bytes metro windows8 storagefile
public static Task<byte[]> ReadStorageFileAsync(StorageFile storageFile)
{
    return Task.Run<byte[]>(async () =>
    {
        ulong size = storageFile.Size;
        IInputStream inputStream = await storageFile.OpenForReadAsync();
        DataReader dataReader = new DataReader(inputStream);
        await dataReader.LoadAsync((uint)size);
        byte[] buffer = new byte[(int)size];
        dataReader.ReadBytes(buffer);
        return buffer;
    });
}
Toast调度
删除
ToastNotifier notifier = ToastNotificationManager.CreateToastNotifier();
                    IReadOnlyList<ScheduledToastNotification> scheduled = notifier.GetScheduledToastNotifications();
                    for (int j = 0; j < scheduled.Count; j++)
                    {
                        if (scheduled[j].Id == itemId)
                        {
                            notifier.RemoveFromSchedule(scheduled[j]);
                        }
                    }
添加:
ScheduledToastNotification toast = new ScheduledToastNotification(toastContent.GetXml(), dueTime, TimeSpan.FromSeconds(60), 5);
ToastNotificationManager.CreateToastNotifier().AddToSchedule(toast);
获取坐标制作Rect
 在下列標記範例中,示範了包含在 StackPanel 物件中的 TextBlock。
C#
<StackPanel Name="myStackPanel" Margin="8"> <TextBlock Name="myTextBlock" Margin="4" Text="Hello, world" /> </StackPanel> 
在下列程式碼範例中,示範了如何使用 TransformToVisual 方法,擷取 StackPanel 相對於其子 TextBlock 的位移。位移值含在傳回的 GeneralTransform 值中。
C#
// Return the general transform for the specified visual object. GeneralTransform generalTransform1 = myStackPanel.TransformToVisual(myTextBlock);  // Retrieve the point value relative to the child. Point currentPoint = generalTransform1.Transform(new Point(0, 0)); 
位移會將所有物件的 Margin 值納入考量。在這個案例中,X 為 -4,而 Y 也為 -4。位移值是負值,因為父物件相對於其子物件的位移是負的。
 
若取myStackPanel相对于 应用程序左上角的  绝对位置,如下:
// Return the general transform for the specified visual object.
GeneralTransform generalTransform1 = myStackPanel.TransformToVisual(null);

// Retrieve the point value relative to the child.
Point currentPoint = generalTransform1.Transform(new Point(0, 0));
 
可以把generalTransform1=myStackPanel.TransformToVisual(myTextBlock);理解为两个对象的坐标变换差值
generalTransform1.Transform(new Point(0, 0));这是把这个坐标变换差值再应用在new Point(0, 0)这个点上





Rect GetElementRect(FrameworkElement element)
        {
            GeneralTransform buttonTransform = element.TransformToVisual(null);
            Point point = buttonTransform.TransformPoint(new Point());
            return new Rect(point, new Size(element.ActualWidth, element.ActualHeight));
        }
获取Rect后可以交给Popup的PlacementRectangle
xaml中事件触发动画
<StackPanel Grid.Column="1">
            <StackPanel.Triggers>
                <EventTrigger RoutedEvent="StackPanel.Loaded"> <!-- 此处的事件必须为StackPanel的事件-->
                    <EventTrigger.Actions>
                        <BeginStoryboard>
                            <Storyboard >
                                <DoubleAnimation Storyboard.TargetName="myRectangle" Storyboard.TargetProperty="Width"  From="200" To="100" Duration="0:0:2" />
                            </Storyboard>
                        </BeginStoryboard>
                        </EventTrigger.Actions>
                </EventTrigger>
            </StackPanel.Triggers>
            <StackPanel.Resources>
</StackPanel.Resources>
            <Button x:Name="myRectangle" Click="Rectangle_Tapped" Background="Blue" Width="200" Height="30" Foreground="Beige" Content="55555"  />              
            
        </StackPanel>
xaml定义动画,手动触发
 <!--KeySpline是贝塞尔曲线的两个控制点,输入不同的值,可以绘制出不同的贝塞尔曲线,那么它的斜率就是加减或则速率为0,斜率越大速度越快,斜率为0,速度为0-->
<StackPanel Grid.Column="1">
            <StackPanel.Resources>
                <!-- 在某个容器或者控件中定义动画名称,这样就可以在代码中引用并开始动画-->
                <Storyboard x:Name="myStoryboard2">
                    <DoubleAnimationUsingKeyFrames EnableDependentAnimation="True"
              Storyboard.TargetName="myRectangle"
              Storyboard.TargetProperty="Height">
                        <!-- This key frame resets the animation to its starting
                 value (30) at the beginning of the animation. -->
                        <LinearDoubleKeyFrame Value="30" KeyTime="0:0:0" />
                        <!-- Spline animations are used to create acceleration. This
                 SplineDoubleKeyFrame creates an animation that starts out slow
                 and then speeds up. The rectangle "falls". -->
                        <SplineDoubleKeyFrame KeySpline="0,0 1,0" Value="300" KeyTime="0:0:0.8" />
                        <!-- This spline animation creates the "bounce" at the end where
                 the rectangle shortens its length quickly at first and then
                 slows down and stops. -->
                        <SplineDoubleKeyFrame KeySpline="0.10, 0.21 0.00, 1.0" Value="250"
                 KeyTime="0:0:1.5" />
                    </DoubleAnimationUsingKeyFrames>
                </Storyboard>
            </StackPanel.Resources>
            <Button x:Name="myRectangle" Click="Rectangle_Tapped" Background="Blue" Width="200" Height="30"/>
 </StackPanel>

代码中引用:

 private void Rectangle_Tapped(object sender, RoutedEventArgs e)
        {
            myStoryboard2.Begin();
        }
Global site tag (gtag.js) - Google Analytics