我正在尝试制作一个可以进行特殊渲染的WPF UIElement
。
问题是我无法使用数据绑定工作PointCollection
。在OnRender()
的{{1}}内,Points属性为null,这对我没有任何意义。
GraphElement
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>
答案 0 :(得分:2)
将GraphElement
上的继承从UIElement
更改为FrameworkElement
(继承UIElement
)。这是您拥有DataContext
dp等的地方。
class GraphElement : FrameworkElement
{
//...
}
将您的代码复制到示例项目中(将UIElement更改为FrameworkElement)并且OnRender中的Points不为null。上传了项目here。