-3

我有这个 xaml 代码,需要从 C# 代码动态设置点。

<Style x:Key="Mystyle" TargetType="Button">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Grid>

                            <Polygon  Points="0,0 0,100 50,200" Fill="{TemplateBinding Background}"
                         Stroke="{TemplateBinding BorderBrush}"/>
                        <ContentPresenter HorizontalAlignment="Center"
                                      VerticalAlignment="Center"/>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
4

1 回答 1

1

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); }
        }
    }       
}
于 2012-07-21T21:28:01.620 回答