创建一个依赖属性 (illustrated WPF 中的一个例子)

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <TextBox TextChanged="TextBox_TextChanged" Name="input">0</TextBox>
        <Grid>
            <Polygon Name="poly" Stroke="Black" Fill="LightGray"></Polygon>
        </Grid>
    </StackPanel>
</Window>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication1
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public static readonly DependencyProperty SideProperty;
        public int Sides {
            get { return (int)GetValue(SideProperty); }
            set { SetValue(SideProperty, value); }
        }
        static MainWindow() {
            FrameworkPropertyMetadata md = new FrameworkPropertyMetadata();
            md.PropertyChangedCallback = OnsidesChanged;
            SideProperty = DependencyProperty.Register("Sides",
                typeof(int),typeof(MainWindow),md);
        
        }
        public MainWindow()
        {
            InitializeComponent();
        }

        private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            int sideCount;
            bool sucess = int.TryParse(input.Text, out sideCount);
            if (sucess && sideCount > 2) {
                Sides = sideCount;
            }
        }
        static void OnsidesChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args) {
            MainWindow mw = obj as MainWindow;
            const int xCenter = 65;
            const int yCenter = 50;
            const int radius=40;
            double rads = Math.PI / mw.Sides * 2;
            mw.poly.Points.Clear();
            mw.poly.Points.Add(new Point(xCenter + radius, yCenter));
            for (double i = 1; i <= mw.Sides - 1;i++ )
            {
                double x = (Math.Cos(rads * i) * radius) + xCenter;
                double y = (Math.Sin(rads * i) * radius) + yCenter;
                mw.poly.Points.Add(new Point(x, y));
            }

        }
    }
}


运行截图

更改数字,多边形自动更新

 

posted @ 2014-11-08 18:09  angrycoder  阅读(316)  评论(0)    收藏  举报