[英]UWP c# Dynamically change chart when changing data
我正在嘗試制作一個圖表(UWP-c#),該圖表在源數據更改時會動態更改。
例如:
xaml文件:
<StackPanel>
<Button Name="scatterButton" Content="click" Click="ScatterButton_Click" />
<Charting:Chart x:Name="test_chart">
<Charting:ScatterSeries IndependentValuePath="Name" DependentValuePath="Amount" />
</Charting:Chart>
</StackPanel>
C#:
public class SmartPhone
{
public string Name { get; set; }
public int Amount { get; set; }
public int Other { get; set; }
}
public sealed partial class MainPage : Page
{
List<SmartPhone> lstSource = new List<SmartPhone>
{
new SmartPhone() { Name = "IPhone", Amount = 40, Other = 1 },
new SmartPhone() { Name = "Android", Amount = 30, Other = 1 },
new SmartPhone() { Name = "UWP", Amount = 25, Other = 2 }
};
public MainPage()
{
this.InitializeComponent();
}
private void Page_Loaded(object sender, RoutedEventArgs e)
{
LoadChartContent();
}
private void LoadChartContent()
{
(test_chart.Series[0] as ScatterSeries).ItemsSource = lstSource;
}
private void ScatterButton_Click(object sender, RoutedEventArgs e)
{
lstSource[0].Amount = 10;
}
}
我的想法是,當我單擊“金額”值更改按鈕時,我希望在圖表中看到它的更改。
我嘗試了許多軟件包,但這是UWP中真正為我工作的唯一軟件包。 NuGet是“ WinRTXamlToolkit.Controls.DataVisualization”。 請嘗試專注於“ ScatterSeries”,因為這是我需要的。
謝謝。
首先,您應該使用ObservableCollection
而不是List
來自動通知何時添加或刪除項目。 要通知有關更改,您必須實現INotifyPropertyChanged
並引發PropertyChanged
事件。
XAML:
<Charting:Chart x:Name="test_chart">
<Charting:ScatterSeries ItemsSource="{x:Bind LstSource}" IndependentValuePath="Name" DependentValuePath="Amount" />
</Charting:Chart>
SmartPhone類示例:
public class SmartPhone : INotifyPropertyChanged
{
private int _amount;
public string Name { get; set; }
public int Amount
{
get { return _amount; }
set
{
this._amount = value;
NotifyPropertyChanged();
}
}
public int Other { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
MainPage類:
public sealed partial class MainPage : Page
{
public ObservableCollection<SmartPhone> LstSource
{
get { return lstSource; }
}
private ObservableCollection<SmartPhone> lstSource = new ObservableCollection<SmartPhone>
{
new SmartPhone() {Name = "IPhone", Amount = 10, Other = 1},
new SmartPhone() {Name = "Android", Amount = 30, Other = 1},
new SmartPhone() {Name = "UWP", Amount = 25, Other = 2}
};
public MainPage()
{
this.InitializeComponent();
//LoadChartContent();
}
private void ScatterButton_Click(object sender, RoutedEventArgs e)
{
lstSource[0].Amount = 30;
//lstSource.Add(new SmartPhone{Amount = 10, Name = "asd", Other = 2});
}
}
我希望這就是您所需要的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.