我目前正在为 Ising model 开发一个 GUI (德语维基百科,因为只有右边的图片才真正重要)它应该包含大约 200x200 的旋转元素。我通过以下方式实现了这一点:
<UniformGrid Name="grid" .... />
并在代码中为每次旋转添加一个矩形,如果旋转值发生变化,我会在代码后面进行更新。这不知何故非常慢,我改变了它所以它使用 Binding
<ItemsControl Name="IsingLattice" ItemsSource="{Binding Spins}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Name="grid" ...
...
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<Rectangle Fill={Binding Color} ...
但这又是 - 非常慢。我尝试调试和改进它 3 天,但到目前为止没有成功。
现在的问题是:我的方法错了吗?如果是这样,我应该使用什么?如果不是 - 我怎样才能提高性能?
如果相关,我会用我的模型实现的一些细节更新这篇文章。
编辑:应该可以通过与元素交互来改变单次旋转。这可以通过在实际图形之上的透明层来完成,但也许并不那么难。
最佳答案
您可以编写一个自定义元素(派生自 FrameworkElement
),在内部存储自旋数据,然后通过覆盖 OnRender
方法一次性渲染数据:
public sealed class IsingModel : FrameworkElement
{
readonly bool[] _spinData = new bool[200 * 200];
protected override void OnRender(DrawingContext dc)
{
// use methods of DrawingContext to draw appropriate
// filled squares based on stored spin data
}
protected override void OnMouseDown(MouseButtonEventArgs e)
{
base.OnMouseDown(e);
// work out which "cell" was clicked on and change
// appropriate spin state value in Boolean array
InvalidateVisual(); // force OnRender() call
}
}
这种方法应该比拥有数千个单独的元素更快。我不知道要快多少。
关于c# - 更新元素时的 WPF 性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28364696/