问题
I just created a pie Chart with the WPF Toolkit. I wanted to create a AddIn for MS Dynamics NAV. If I call that method in NAV:
public void setChart(string chartKey, float chartValue)
{
KeyValuePair<string, float> value = new KeyValuePair<string, float>(chartKey, chartValue);
values.Add(value);
}
my Chart is not refreshing. My ObservableCollection is updating but it doesn't Show any Chart. If I just do
setChart("AB123",60);
to the constructor it works.
How can I update the Chart. I also call pieChart.DataContext = values;
in the constructor. If I call it again in setChart it still not work.
Click me: Screenshot
回答1:
You set your values
after initializing your windows and since values
in your example doesn't implement a setter and the INotifyPropertyChanged
manner, your UI thread is never warn by the change you made on your collection.
Use INotifyPropertyChanged
interface:
Like that when you set your items, Your UI thread knows there is a change to do in the xaml part (I took a Window but it can be a Page, a UserControl or a Custom Class)
public partial class MainWindow : Window, INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged = delegate { };
private ObservableCollection<KeyValuePair<string, float>> _values;
public ObservableCollection<KeyValuePair<string, float>> values {
get {
if (_values == null) {
_values = new ObservableCollection<KeyValuePair<string, float>>();
}
return _values;
}
set {
_values = value;
PropertyChanged(this, new PropertyChangedEventArgs(nameof(values)));
}
}
....
I didn't see your code in your xaml maybe there is a change to do here too.
回答2:
Okay to sum up:
You Need to use a ObservableCollection<> instead of an List<>.
The ObservableCollection refreshes automaticly if something changed in it.
public ObservableCollection<KeyValuePair<string, float>> values = new ObservableCollection<KeyValuePair<string, float>>();
This is mine. The answer above is just the same, just alot longer. Maybe in some situations you Need to use it. But in this case I don't see any use of it. But thanks!
The Problem was Dynamics NAV (I'm using 2016). I wanted to Show Items with its amount. The problem was: The amount was always 0 for some reason. And WPF Toolkit Charts don't Show any tiles with the value 0.
But why it was 0? The amount is a decimal (C/AL) and you Need CALCFIELDS. So I just added Rec.CALCFIELDS(field);
and it worked! The value was no longer 0! And the Chart Shows me what I wanted.
Maybe I could helped someone with the same Problem :)
来源:https://stackoverflow.com/questions/42623650/wpf-toolkit-how-to-refresh-a-chart