首页 > 解决方案 > 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
    }
}

标签: c#wpf

解决方案


问题是它PriceChart没有实现任何更改通知。使用当前代码,这就是StockAnalysis创建时的情况:

  1. InitializeComponent()将创建TextBlocks 和绑定。此时,DataContextis null,所以绑定将失败并且TextBlock保持为空。

  2. this.DataContext = PChart将触发绑定更新(因为DataContext是 a DependencyProperty,这意味着它确实支持更改通知)。当绑定更新时,它会拉取LastPrice当前仍然为空的值。

  3. ShowPriceChart将设置 的值LastPrice,但由于PriceChart不支持更改通知,绑定不知道它需要更新,所以TextBlock保持为空。

为了解决这个问题,我建议您按照本文PriceChart实现接口:如何:实现属性更改通知INotifyPropertyChanged

(从技术上讲,移动PChart.ShowPriceChart(HistoricalPrice)之前this.DataContext = PChart也可以“解决”问题,但前提是您不需要在初始化后再次更新绑定。)


推荐阅读