ビューを 1 秒間に最大 30 回更新する WPF のプロジェクトに取り組んでいます。私は自分の知る限り MVVM パターンを採用しており、これまでの結果にはかなり満足しています。ただし、ホスト コンテナーの VisualCollection 内で DrawingVisuals を更新するより効率的な方法がないかどうか疑問に思っています。ビューモデルのプロパティが変更されるたびに、そのビューモデルの新しい DrawingVisual を見つけて削除し、再度追加しています。常に移動するオブジェクトでは、DrawingVisuals 自体をビューモデルのプロパティに直接バインドするなど、より良い方法があるはずだと思いますが、それはどのように見えるでしょうか? シミュレーション内のモデルの数が増えるにつれて、更新のための合理化されたワークフローを確保する必要があります。ここの例に従って始めました: http://msdn.microsoft.com/en-us/library/ms742254。
非常に効率的な描画キャンバスが必要なため、DependencyProperties と UserControls をすべてのビューモデルにバインドすることを意図的に避けています (したがって、以下の QuickCanvas です)。そのため、メインの UI を設計し、ボタンとコマンドを接続する以外に、XAML はほとんど必要ありません。不明な点や重要な点を省略した場合は、質問してください。ありがとう!
視覚的なホスト コンテナー (ビュー):
public partial class QuickCanvas : FrameworkElement
{
private readonly VisualCollection _visuals;
private readonly Dictionary<Guid, DrawingVisual> _visualDictionary;
public static readonly DependencyProperty ItemsSourceProperty =
DependencyProperty.Register("ItemsSource", typeof(ObservableNotifiableCollection<IVisualModel>),
typeof(QuickCanvas),
new PropertyMetadata(OnItemsSourceChanged));
public QuickCanvas()
{
InitializeComponent();
_visuals = new VisualCollection(this);
_visualDictionary = new Dictionary<Guid, DrawingVisual>();
}
public ObservableNotifiableCollection<IVisualModel> ItemsSource
{
set { SetValue(ItemsSourceProperty, value); }
get { return (ObservableNotifiableCollection<IVisualModel>)GetValue(ItemsSourceProperty); }
}
protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
{
base.OnPropertyChanged(e);
if (e.Property.Name == "Width" || e.Property.Name == "Height" || e.Property.Name == "Center")
{
UpdateVisualChildren();
}
}
private void UpdateVisualChildren()
{
if (ItemsSource == null || _visuals.Count == 0) return;
foreach (var model in ItemsSource)
{
var visual = FindVisualForModel(model);
if (visual != null)
{
UpdateVisualFromModel(visual, model);
}
}
}
private void UpdateVisualPairFromModel(DrawingVisual visual, IVisualModel model)
{
visual.Transform = ApplyVisualTransform(visual.Transform, model);
}
private static void OnItemsSourceChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
(obj as QuickCanvas).OnItemsSourceChanged(args);
}
private void OnItemsSourceChanged(DependencyPropertyChangedEventArgs args)
{
_visuals.Clear();
if (args.OldValue != null)
{
var models = args.OldValue as ObservableNotifiableCollection<IVisualModel>;
models.CollectionCleared -= OnCollectionCleared;
models.CollectionChanged -= OnCollectionChanged;
models.ItemPropertyChanged -= OnItemPropertyChanged;
}
if (args.NewValue != null)
{
var models = args.NewValue as ObservableNotifiableCollection<IVisualModel>;
models.CollectionCleared += OnCollectionCleared;
models.CollectionChanged += OnCollectionChanged;
models.ItemPropertyChanged += OnItemPropertyChanged;
CreateVisualChildren(models);
}
}
private void OnCollectionCleared(object sender, EventArgs args)
{
_visuals.Clear();
_visualDictionary.Clear();
}
private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs args)
{
if (args.OldItems != null)
RemoveVisualChildren(args.OldItems);
if (args.NewItems != null)
CreateVisualChildren(args.NewItems);
}
private void OnItemPropertyChanged(object sender, ItemPropertyChangedEventArgs args)
{
var model = args.Item as IVisualModel;
if (model == null)
throw new ArgumentException("args.Item was expected to be of type IVisualModel but was not.");
//TODO is there a better way to update without having to add/remove visuals?
var visual = FindVisualForModel(model);
_visuals.Remove(visual);
visual = CreateVisualFromModel(model);
_visuals.Add(visual);
_visualDictionary[model.Id] = visual;**
}
private DrawingVisual FindVisualForModel(IVisualModel model)
{
return _visualDictionary[model.Id];
}
private void CreateVisualChildren(IEnumerable models)
{
foreach (IVisualModel model in models)
{
var visual = CreateVisualFromModel(model);
_visuals.Add(visual);
_visuals.Add(visual);
_visualDictionary.Add(model.Id, visual);
}
}
private DrawingVisual CreateVisualFromModel(IVisualModel model)
{
var visual = model.GetVisual();
UpdateVisualFromModel(visual, model);
return visual;
}
private void RemoveVisualChildren(IEnumerable models)
{
foreach (IVisualModel model in models)
{
var visual = FindVisualForModel(model);
if (visual != null)
{
_visuals.Remove(visual);
_visualDictionary.Remove(model.Id);
}
}
}
protected override int VisualChildrenCount
{
get
{
return _visuals.Count;
}
}
protected override Visual GetVisualChild(int index)
{
if (index < 0 || index >= _visuals.Count)
throw new ArgumentOutOfRangeException("index");
return _visuals[index];
}
}
IVisuaModel impl:
public class VehicleViewModel : IVisualModel
{
private readonly Vehicle _vehicle;
private readonly IVisualFactory<VehicleViewmodel> _visualFactory;
private readonly IMessageBus _messageBus;
public VehicleViewmodel(Vehicle vehicle, IVisualFactory<VehicleViewmodel> visualFactory, IMessageBus messageBus)
{
_vehicle = vehicle;
_visualFactory = visualFactory;
_messageBus = messageBus;
_messageBus.Subscribe<VehicleMovedMessage>(VehicleMoveHandler, Dispatcher.CurrentDispatcher);
Id = Guid.NewGuid();
}
public void Dispose()
{
_messageBus.Unsubscribe<VehicleMovedMessage>(VehicleMoveHandler);
}
private void VehicleMoveHandler(VehicleMovedMessage message)
{
if (message.Vehicle.Equals(_vehicle))
OnPropertyChanged("");
}
public Guid Id { get; private set; }
public Point Anchor { get { return _vehicle.Position; } }
public double Rotation { get { return _vehicle.Orientation; } }
public DrawingVisual GetVisual()
{
return _visualFactory.Create(this);
}
public double Width { get { return _vehicle.VehicleType.Width; } }
public double Length { get { return _vehicle.VehicleType.Length; } }
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
IVisualFactory 実装:
public class VehicleVisualFactory : IVisualFactory<VehicleViewModel>
{
private readonly IDictionary<string, Pen> _pens;
private readonly IDictionary<string, Brush> _brushes;
public VehicleVisualFactory(IDictionary<string, Pen> pens, IDictionary<string, Brush> brushes)
{
_pens = pens;
_brushes = brushes;
}
public DrawingVisual Create(VehicleViewmodel viewModel)
{
var result = new DrawingVisual();
using (var context = result.RenderOpen())
{
context.DrawRectangle(_brushes["VehicleGreen"], _pens["VehicleDarkGreen"],
new Rect(-viewModel.Width / 2, -viewModel.Length / 2, viewModel.Width, viewModel.Length));
}
return result;
}
}