MVVM 解决方案:
XAML 文件:
<Window x:Class="PolygonBinding.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">
<Window.Resources>
<Style x:Key="Mystyle" TargetType="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Grid>
<Polygon Points="{TemplateBinding Tag}" Fill="{TemplateBinding Background}"
Stroke="{TemplateBinding BorderBrush}"/>
<ContentPresenter HorizontalAlignment="Center"
VerticalAlignment="Center"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<Button Style="{StaticResource Mystyle}" Tag="{Binding PointsSource}" />
</Grid>
</Window>
代码隐藏文件:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new MainViewModel();
}
}
视图模型文件:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Prism.ViewModel;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Media;
namespace PolygonBinding
{
class MainViewModel : NotificationObject
{
public MainViewModel()
{
PointsSource.Add(new Point { X = 0, Y =0 });
PointsSource.Add(new Point { X = 0, Y = 100 });
PointsSource.Add(new Point { X = 50, Y = 200 });
}
private PointCollection _pointsSource = new PointCollection();
public PointCollection PointsSource
{
get { return _pointsSource; }
set { _pointsSource = value; RaisePropertyChanged(() => PointsSource); }
}
}
}