Skip to main content
 首页 » 编程设计

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

2024年02月13日12shihaiming

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

可视化窗口.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 不能优雅地做到这一点,其他库是否可以更轻松地做到这一点。

请您参考如下方法:

将 ItemsSource 处理添加到现有类。

他们似乎已竭尽全力让 ChartPlotter 只接受 IPlotterElements。没有 ItemsSource 属性,因此 Children 将始终返回实际元素。 RectangleHighlight 的 Bounds 属性不可绑定(bind)且该类是密封的,禁止任何方法覆盖该属性。

我们可以从类派生来“注入(inject)” ItemsSource 处理。它不会像真正的交易那样工作,因为没有简单的方法让 Children 属性反射(reflect)数据绑定(bind)。但是,我们仍然可以通过这种方式分配 ItemsSource。

我们需要一些东西。我们需要实际的 ItemsSource 属性。一种对其设置使用react的方法。如果我们想绑定(bind)到 dataObjects,一种处理 DataTemplates 的方法。我还没有深入研究现有的源代码。但是,我确实想出了一种无需 DataTemplateSelector 即可处理 DataTemplates 的方法。但除非您修改我的示例,否则它也不适用于 DataTemplateSelector。

此答案假设您了解绑定(bind)的工作原理,因此我们将直接跳到初始类(class),无需太多指导。

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 的数据绑定(bind)。

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 属性不能是数据绑定(bind)的。您也无法从它们派生来解决这个问题。

我们可以通过提取数据模板并生成静态 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 的事件来解决这个问题。每当集合发生变化时,我都会使用一个简单的方法来重新绑定(bind)控件。不过,这仅在 ItemsSource 由 ObservableCollection 分配时才有效。但我认为这与没有 ObservableCollection 的 ItemsControl 会有同样的问题。

但是,我们仍然没有重新分配 dataContext。所以不要指望改变 Children 会正确地重新绑定(bind)。但是,如果您直接更改子项,而不是 ItemsControl 中的 ItemsSource,您将失去绑定(bind)。所以我很可能走上正轨。我们失去的唯一怪癖是,当您在设置 ItemsSource 后引用 Children 时,ItemsControl 返回 ItemsSource。我还没有解决这个问题。我唯一能想到的就是隐藏 children 属性,但这不是一件好事,如果您将控件称为 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;