c# - WPF C# 绑定来自另一个类的数据
问题描述
所以我错过了一些简单的东西或失去了理智。我正在尝试为 WPF 应用程序中的多个页面重用一个类,并将属性绑定到实例化它的页面。我试过设置 DataContext 但我错过了一些东西。我正在加载 StockAnalysis 页面,然后创建 PriceChart 类的实例(这是用于重用的类),并且我希望 PriceChart 类中设置的属性成为绑定到 Stock.xaml.cs 页面的数据。即使在设置 DataContext 时,它仍在寻找 StockAnalysis 对象。为什么?
Stock.xaml.cs
public partial class StockAnalysis : Page
{
PriceChart PChart = new PriceChart();
public StockAnalysis()
{
InitializeComponent();
//Load The Data
List<Stock> HistoricalPrice = Database.GetPrices(ticker);
//Create The Charts
this.DataContext = PChart;
PChart.ShowPriceChart(HistoricalPrice);
}
}
Stock.xaml(查看“LastPrice”绑定的最后一个 TexBlock)
<Page x:Class="Stock.StockAnalysis"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:lvc="clr-namespace:LiveCharts.Wpf;assembly=LiveCharts.Wpf"
xmlns:local="clr-namespace:Stock"
mc:Ignorable="d"
d:DesignHeight="1000" d:DesignWidth="1200"
Title="Stock Analysis">
<StackPanel x:Name="LastClosePanel" Grid.Row="0" Grid.RowSpan="2" Grid.Column="5" Height="60" VerticalAlignment="Top" Margin="1,0,0,1" Style="{StaticResource LastCloseBackground}">
<TextBlock x:Name="LastCloseText" Foreground="OrangeRed" FontSize="12" HorizontalAlignment="Center" Margin="0,10,0,8">Last Close</TextBlock>
<TextBlock x:Name="LastCloseBind" Foreground="White" FontSize="16" HorizontalAlignment="Center" Text="{Binding LastPrice}"></TextBlock>
</StackPanel>
</Page>
PriceChart.cs(这是我指定“LastPrice”的地方,希望将其绑定到 stock.xaml.cs 中的 TextBlock)
public class PriceChart
{
public string LastPrice { get; set; }
public void ShowPriceChart(List<Stock> FullList)
{
LastPrice = FullList[0].LastPrice.ToString("C");
//DO OTHER THINGS
}
}
解决方案
问题是它PriceChart
没有实现任何更改通知。使用当前代码,这就是StockAnalysis
创建时的情况:
InitializeComponent()
将创建TextBlock
s 和绑定。此时,DataContext
isnull
,所以绑定将失败并且TextBlock
保持为空。this.DataContext = PChart
将触发绑定更新(因为DataContext
是 aDependencyProperty
,这意味着它确实支持更改通知)。当绑定更新时,它会拉取LastPrice
当前仍然为空的值。ShowPriceChart
将设置 的值LastPrice
,但由于PriceChart
不支持更改通知,绑定不知道它需要更新,所以TextBlock
保持为空。
为了解决这个问题,我建议您按照本文PriceChart
实现接口:如何:实现属性更改通知。INotifyPropertyChanged
(从技术上讲,移动PChart.ShowPriceChart(HistoricalPrice)
之前this.DataContext = PChart
也可以“解决”问题,但前提是您不需要在初始化后再次更新绑定。)
推荐阅读
- r - R中列表的比较
- r - 如何为两个分类变量创建列联表(交叉表)?
- video - 有没有一种简单有效的方法来读取文件并将它们转换为指定的 DXGI_Format 并解码输出大小?
- asp.net-mvc - 添加 turf.js 脚本标签
- node.js - 当 html 被先前的 ajax 发布操作的结果替换时,Ajax 发布操作不起作用
- javascript - ForEach 循环仅将最后一个值应用于变量
- excel - 使用 Excel VBA 是否可以将整个工作表的 NumberFormat 复制到新工作表?
- python - SocketIo 与 Django 的集成
- python - 仅使用 randint 创建指定范围内的随机偶数列表
- paraview - 导出顶点连接(三角形)和顶点颜色