动态数据显示可变数量矩形的图形

时间:2013-03-13 21:37:21

标签: c# wpf data-binding graph dynamic-data-display

我正在尝试绘制用户的输入数据,这些数据最终将成为图形中的一系列矩形(不同的大小和位置,不重叠)。我读过的所有例子都只绘制了具有可变数量点的线或XAML中的形状中的硬编码。但我不知道数据需要多少个矩形。我理想的情况是遵循MVVM并简单地从XAML绑定到我可以修改的ObservableCollection,但我看到的大多数示例似乎都使用代码隐藏,直接访问ChartPlotter。这是我用一些简单的矩形绘制和一个修改后的工作:

VisualizationWindow.xaml

<Window x:Class="View.VisualizationWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d3="http://research.microsoft.com/DynamicDataDisplay/1.0"
        Title="VisualizationWindow" MinHeight="300" MinWidth="500" Height="300" Width="500">
    <Grid>
        <d3:ChartPlotter Name="Chart">
            <d3:RectangleHighlight Name="Rect1" Bounds="-1,-1.5,.5,2" StrokeThickness="3" Fill="Blue" ToolTip="Blue!"></d3:RectangleHighlight>
            <d3:RectangleHighlight Name="Rect2" Bounds="1,1.5,2,.5" StrokeThickness="1" Fill="Red" ToolTip="Red!"></d3:RectangleHighlight>
        </d3:ChartPlotter>
    </Grid>
</Window>

VisualizationWindow.xaml.cs

public partial class VisualizationWindow : Window
{
    public VisualizationWindow(ListViewModel vm)
    {
        InitializeComponent();
        this.DataContext = vm;

        Chart.Viewport.Visible = new Rect(-1, -1, .5, .5);

        Rect1.Bounds = new Rect(0,0,.3,.3);
    }
}

动态数据显示的文档几乎不存在。我很想知道如果D3不能优雅地做到这一点,其他图书馆是否可以更容易地做到这一点。

1 个答案:

答案 0 :(得分:4)

将ItemsSource处理添加到现有类。

看起来他们已经做了一切使ChartPlotter只接受IPlotterElements。没有ItemsSource属性,因此Children将始终返回实际元素。 RectangleHighlight的Bounds属性不可绑定,并且类被密封,禁止任何方法覆盖属性。

我们可以从类派生到“注入”ItemsSource处理。它不会像真正的交易一样工作,因为没有非hackish方式让Children属性反映数据绑定。但是,我们仍然可以这样分配ItemsSource。

我们需要一些东西。我们需要实际的ItemsSource属性。一种对它进行反应的方法。如果我们想要绑定到dataObjects,那么处理DataTemplates的方法。我还没有深入研究现有的源代码。但是,我确实提出了一种在没有DataTemplateSelector的情况下处理DataTemplates的方法。但除非您修改我的示例,否则它也不适用于DataTemplateSelector。

这个答案假设您知道绑定是如何工作的,所以我们将跳过初始类而不需要太多手持。

首先是Xaml:

<local:DynamicLineChartPlotter Name="Chart" ItemsSource="{Binding DataCollection}">
    <local:DynamicLineChartPlotter .Resources>
        <DataTemplate DataType{x:Type local:RectangleHighlightDataObject}>
            <d3:RectangleHighlight 
                Bounds="{Binding Bounds}" 
                StrokeThickness="{Binding StrokeThickness}"
                Fill="{Binding Fill}"
                ToolTip="{Binding ToolTip}"
            />
        </DataTemplate>
    </local:DynamicLineChartPlotter .Resources>
</local:DynamicLineChartPlotter >

类:

public class RectangleHighlightDataObject
{
    public Rect Bounds { get; set; }
    public double StrokeThickness { get; set; }
    public Brush Fill { get; set; }
    public String ToolTip { get; set; }
}


public class VisualizationWindow
{
    public VisualizationWindow() 
    {
         DataCollection.Add(new RectangleHighlightDataObject()
         {
             Bounds = new Rect(-1,-1.5,.5,2),
             StrokeThickness = 3,
             Fill = Brushes.Blue,
             ToolTip = "Blue!"
         });

         DataCollection.Add(new RectangleHighlightDataObject()
         {
             Bounds = new Rect(1,1.5,2,.5),
             StrokeThickness = 1,
             Fill = Brushes.Red,
             ToolTip = "Red!"
         });
    }
    public ObservableCollection<RectangleHighlightDataObject> DataCollection = 
             new ObservableCollection<RectangleHighlightDataObject>();
}

您必须使用ChartPlotter中的派生类,而不是实现ItemsSource。

a discussion on how to implement dynamic D3 types收集的一个例子。我修改为使用DataTemplates而不是实际的对象元素,这是为了支持OP的数据绑定。

public class DynamicLineChartPlotter : Microsoft.Research.DynamicDataDisplay.ChartPlotter
{
    public static DependencyProperty ItemsSourceProperty =
            DependencyProperty.Register("ItemsSource",
                                        typeof(IEnumerable),
                                        typeof(DynamicLineChartPlotter),
                                        new FrameworkPropertyMetadata(null, new PropertyChangedCallback(OnItemsSourceChanged)));

    [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Bindable(true)]
    public IEnumerable ItemsSource
    {
        get
        {
            return (IEnumerable)GetValue(ItemsSourceProperty);
        }
        set
        {
            if (value == null)
                ClearValue(ItemsSourceProperty);
            else
                SetValue(ItemsSourceProperty, value);
        }
    }

    private static void OnItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        DynamicLineChartPlotter control = (DynamicLineChartPlotter)d;
        IEnumerable oldValue = (IEnumerable)e.OldValue;
        IEnumerable newValue = (IEnumerable)e.NewValue;

        if (e.OldValue != null)
        {
            control.ClearItems();
        }
        if (e.NewValue != null)
        {
            control.BindItems((IEnumerable)e.NewValue);
        }
    }

    private void ClearItems()
    {
        Children.Clear();
    }

    private void BindItems(IEnumerable items)
    {
        foreach (var item in items)
        {
            var template = GetTemplate(item);
            if (template == null) continue;

            FrameworkElement obj = template.LoadContent() as FrameworkElement;
            obj.DataContext = item;
            Children.Add((IPlotterElement)obj);
        }
    }

    private DataTemplate GetTemplate(object item)
    {
        foreach (var key in this.Resources.Keys)
        {
            if (((DataTemplateKey)key).DataType as Type == item.GetType())
            {
                return (DataTemplate)this.Resources[key];
            }
        }
        return null;
    }
}

现在,这就是你打砖墙的地方。

RectangleHighlight Bounds属性不能是数据绑定的。你也无法从他们那里得到解决这个问题。

我们可以通过拉出数据模板并生成静态RectangleHighlight来解决问题,但如果数据值发生变化,我们就会解决问题。

那么,如何解决这个问题?

好吧,我们可以使用附加属性!

使用附加属性

我们将创建一个静态类来处理附加属性。它响应OnPropertyChanged以手动创建和设置不动产。现在,这只会以一种方式运作。如果您碰巧更改了该属性,则不会更新附加属性。但是,这应该不是问题,因为我们应该只更新我们的数据对象。

添加此课程

public class BindableRectangleBounds : DependencyObject
{
    public static DependencyProperty BoundsProperty = DependencyProperty.RegisterAttached("Bounds", typeof(Rect), typeof(BindableRectangleBounds), new PropertyMetadata(new Rect(), OnBoundsChanged));

    public static void SetBounds(DependencyObject dp, Rect value)
    {
        dp.SetValue(BoundsProperty, value);
    }
    public static void GetBounds(DependencyObject dp)
    {
        dp.GetValue(BoundsProperty);
    }

    public static void OnBoundsChanged(DependencyObject dp, DependencyPropertyChangedEventArgs args)
    {
        var property = dp.GetType().GetProperty("Bounds");
        if (property != null)
        {
            property.SetValue(dp, args.NewValue, null);
        }
    }
}

然后从

更改XAML行
                Bounds="{Binding Bounds}" 

                local:BindableRectangleBounds.Bounds="{Binding Bounds}" 

对集合的回应发生了变化。

到目前为止一切顺利。但OP注意到,如果他对集合中的ItemsSource进行了更改,则控件中没有任何变化。那是因为我们只在分配ItemsSource时添加子项。现在,除非确切知道ItemsControl如何实现ItemsSource。我知道我们可以通过在集合更改时注册ObservableCollection的事件来解决这个问题。每当集合发生变化时,我都会使用一种简单的方法来重新绑定控件。这只有在ItemsSource由ObservableCollection指定的情况下才有效。但我认为这与ItemsControl没有ObservableCollection会有同样的问题。

但是我们仍然没有重新分配dataContext。因此,不要指望改变儿童会正确重新绑定。但是,如果您确实直接更改了子项,而不是ItemsControl中的ItemsSource,则会丢失绑定。所以我可能会走上正轨。我们失去的唯一怪癖是ItemsControl在设置ItemsSource后引用Children时返回ItemsSource。我还没有解决过这个问题。我唯一可以想到的就是隐藏子属性,但这不是一件好事,如果你将控件称为ChartPlotter则无法工作。

添加以下

    public DynamicLineChartPlotter()
    {
        _HandleCollectionChanged = new NotifyCollectionChangedEventHandler(collection_CollectionChanged);
    }

    private static void OnItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        DynamicLineChartPlotter control = (DynamicLineChartPlotter)d;
        IEnumerable oldValue = (IEnumerable)e.OldValue;
        IEnumerable newValue = (IEnumerable)e.NewValue;
        INotifyCollectionChanged collection = e.NewValue as INotifyCollectionChanged;
        INotifyCollectionChanged oldCollection = e.OldValue as INotifyCollectionChanged;

        if (e.OldValue != null)
        {
            control.ClearItems();
        }
        if (e.NewValue != null)
        {
            control.BindItems((IEnumerable)e.NewValue);
        }
        if (oldCollection != null)
        {
            oldCollection.CollectionChanged -= control._HandleCollectionChanged;
            control._Collection = null;
        }
        if (collection != null)
        {
            collection.CollectionChanged += control._HandleCollectionChanged;
            control._Collection = newValue;
        }
    }

    void collection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        ClearItems();
        BindItems(_Collection);
    }

    NotifyCollectionChangedEventHandler _HandleCollectionChanged;
    IEnumerable _Collection;