我正在使用的图表工具在mvvm中不支持绑定(bind)。因此,我决定使用一种消息传递服务(例如MVVM Light的消息传递框架),以便每次更新viewmodel observablecollection时都会发送一条消息,该消息在接收到时会向图表添加数据点(这将是不幸的是在后面的代码中)。你们看到这个计划有什么问题吗?
最佳答案
我个人认为,对于您想要实现的目标来说,消息传递有点过分,尽管如此。您不能使用适配器或附加的行为模式吗?这就是他们通常用来替代缺少的功能的东西。如果您可以在Xaml中实例化图表(我希望这样做),建议您使用附加行为,否则,请使用和apater(对于没有公共(public)构造函数或任何其他棘手内容的元素)并在代码中实例化。
对于支持命令式调用的任何类,只有您始终可以提出补偿行为。这是一个快速示例:
代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public Dictionary<int, int> MyValues
{
get
{
return Enumerable.Range(1, 3).ToDictionary(k => k, v => v);
}
}
}
// component with the 'missing' property
public class Imperative : FrameworkElement
{
public void Add(int x, int y)
{
MessageBox.Show(string.Format("{0}_{1}", x, y));
}
}
// compensating behavior
public class DeclarativeBehavior : DependencyObject
{
public static DependencyProperty MissingPropertyProperty =
DependencyProperty.RegisterAttached("MissingProperty",
typeof(Dictionary<int, int>),
typeof(DeclarativeBehavior),
new PropertyMetadata((o, e) =>
{
//
Imperative imperative = (Imperative)o;
Dictionary<int, int> values = (Dictionary<int, int>)e.NewValue;
if (imperative != null)
{
foreach (KeyValuePair<int, int> value in values)
{
imperative.Add(value.Key, value.Value);
}
}
}));
public static void SetMissingProperty(DependencyObject o, Dictionary<int, int> e)
{
o.SetValue(DeclarativeBehavior.MissingPropertyProperty, e);
}
public static Dictionary<int, int> GetMissingProperty(DependencyObject o)
{
return (Dictionary<int, int>)o.GetValue(DeclarativeBehavior.MissingPropertyProperty);
}
}
}
XAML
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="525">
<Grid>
<!--black box, which supports imperative calls is extended to support declarative calls too-->
<local:Imperative local:DeclarativeBehavior.MissingProperty="{Binding MyValues,
RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
</Grid>
</Window>
关于c# - 如何处理不支持绑定(bind)的图表?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8589227/