我將使用按鈕更新圖表上的資料。我試圖找到并解決各種案例,但都沒有成功。
這是 XAML 代碼
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="1*"/>
<RowDefinition Height="12*"/>
</Grid.RowDefinitions>
<Button Click="StartChart">
Start
</Button>
<lvc:CartesianChart Series="{Binding Series}"
Grid.Row="1">
<lvc:CartesianChart.AxisX>
<lvc:Axis LabelFormatter="{Binding Formatter}"></lvc:Axis>
</lvc:CartesianChart.AxisX>
</lvc:CartesianChart>
</Grid>
這是代碼背后
public void StartChart(object sender, RoutedEventArgs e)
{
var dayConfig = Mappers.Xy<DateModel>()
.X(dayModel => (double)dayModel.DateTime.Ticks / TimeSpan.FromHours(1).Ticks)
.Y(dayModel => dayModel.Value);
Series = new SeriesCollection(dayConfig)
{
new LineSeries
{
Values = new ChartValues<DateModel>
{
new DateModel
{
DateTime = DateTime.Now,
Value = value1
},
new DateModel
{
DateTime = DateTime.Now.AddMinutes(30),
Value = value2
},
new DateModel
{
DateTime = DateTime.Now.AddHours(1),
Value = value3
},
new DateModel
{
DateTime = DateTime.Now.AddHours(2),
Value = value4
}
},
Fill = Brushes.Transparent
}
};
Formatter = value => new DateTime((long)(value * TimeSpan.FromHours(4).Ticks)).ToString("t");
value1 ;
value2--;
value3 ;
value4--;
DataContext = this;
}
public Func<double, string> Formatter { get; set; }
public SeriesCollection Series { get; set; }
每次單擊按鈕時,您都希望圖表的值發生變化。請給我一個解決方案。
uj5u.com熱心網友回復:
你想用
public static readonly DependencyProperty FormatterProperty = DependencyProperty.Register(
nameof(Formatter), typeof(Func<double, string>), typeof(MainWindow), new PropertyMetadata(default(Func<double, string>)));
并更改public Func<double, string> Formatter { get; set; }為
public Func<double, string> Formatter
{
get => (Func<double, string>)GetValue(FormatterProperty);
set => SetValue(FormatterProperty, value);
}
對所有其他 Binding-intended 變數也是如此。
這稱為依賴屬性的資料系結。當 DependecyProperty 值更改時,系結也會更改。這樣你就不需要不斷地重新分配DataContext = this;. 只設定一次 DataContext。DependencyPropertys 完成其余的作業。
此外,您可能想研究 MVVM 模式,在其中您將了解一個您將命名為 ViewModel 并將其設定為 DataContext 的類;并且,不使用 DependencyProperties,而是使用 INotifyPropertyChange 來實作相同的效果。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/409435.html
標籤:
下一篇:物體框架資料播種DateTime
