1

我正在尝试制作一个可以进行UIElement一些特殊渲染的 WPF。

问题是我无法让数据绑定为PointCollection. 在内部OnRender()GraphElementPoints 属性为空,这对我来说没有任何意义。

class GraphElement : UIElement
{
    public static readonly DependencyProperty PointsProperty = DependencyProperty.Register(
        "Points",
        typeof(PointCollection),
        typeof(GraphElement),
        new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender));            

    public PointCollection Points
    {
        get { return (PointCollection)GetValue(PointsProperty); }
        set { SetValue(PointsProperty, value); }
    }

    protected override void OnRender(DrawingContext drawingContext)
    {
        base.OnRender(drawingContext);

        //Points is null
        Debug.Assert(Points != null);
    }

}

class TestViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private PointCollection _viewModelPoints;
    public PointCollection ViewModelPoints
    {
        get { return _viewModelPoints; }
        set
        {
            _viewModelPoints = value;
            if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("ViewModelPoints"));
        }
    }
}

<Window x:Class="TestApp.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:TestApp"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <Canvas>
        <local:GraphElement Points="{Binding Path=ViewModelPoints}"/>
    </Canvas>
</Grid>


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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 TestApp
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            var testViewModel = new TestViewModel();
            testViewModel.ViewModelPoints = new PointCollection();
            testViewModel.ViewModelPoints.Add(new Point(0.0, 0.0));
            DataContext = testViewModel;
            InitializeComponent();
        }
    }
}
4

1 回答 1

2

GraphElement将继承从UIElementto更改为FrameworkElement(进而继承UIElement)。这是您拥有DataContextdp 等的地方。

class GraphElement : FrameworkElement
{
    //...
}

将您的代码复制到示例项目中(将 UIElement 更改为 FrameworkElement),并且 Points 在 OnRender 中不为空。在这里上传了项目。

于 2010-11-28T08:58:42.720 回答