You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF中ListView与TextBlock数据绑定异常:属性更新未实时刷新

加密货币数据程序的数据绑定问题

我正在开发一款存储加密货币数据的程序,但遇到了数据绑定问题:

第一种绑定方式(正常工作)

//Set binding path to Text property
Binding binding = new Binding("Text");
binding.Source = txt;
binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
binding.Mode = BindingMode.TwoWay;
//Attach a binding to the listview which holds the data
lst.SetBinding(ListView.SelectedItemProperty, binding);

第二种绑定方式(存在问题)

改用此方式时,TextBlock不会随属性变更实时更新,仅在重新选择同一ListView项时才更新:

//Set binding path to SelectedItem property
Binding binding = new Binding("SelectedItem");
binding.Source = lst;
binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
binding.Mode = BindingMode.TwoWay;
//Attach a binding to the TextBlock which shows the data below the list
txt.SetBinding(TextBlock.TextProperty, binding);

相关代码片段

构造函数代码

public FilteringSample()
{
    InitializeComponent();
    //Set binding path to Text property
    Binding binding = new Binding("Text");
    binding.Source = txt;
    binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
    binding.Mode = BindingMode.TwoWay;
    //Attach a binding to the listview which holds the data
    lst.SetBinding(ListView.SelectedItemProperty, binding);
    WebClient webClient = new WebClient();
    string data1 = webClient.DownloadString("https://www.coingecko.com/tr/coins/solana");
    string data2 = webClient.DownloadString("https://www.coingecko.com/tr/coins/bitcoin");
    HtmlDocument htmlDocument1 = new HtmlDocument();
    HtmlDocument htmlDocument2 = new HtmlDocument();
    htmlDocument1.LoadHtml(data1);
    string text1= htmlDocument1.DocumentNode.SelectSingleNode("/html/body/div[5]/div[5]/div[1]/div/div[1]/div[3]/div/div[1]/span[1]/span").InnerText;
    htmlDocument2.LoadHtml(data2);
    string text2 = htmlDocument2.DocumentNode.SelectSingleNode("/html/body/div[5]/div[5]/div[1]/div/div[1]/div[3]/div/div[1]/span[1]/span").InnerText;
    ObservableCollection<Currency> list = new ObservableCollection<Currency>();
    list.Add(new Currency(){Name="Solana", RealValue = text1 });
    list.Add(new Currency() { Name = "Bitcoin", RealValue = text2 });
    foreach(Currency cry in list)
    {
        lst.Items.Add(cry);
    }
}

Currency类代码(实现INotifyPropertyChanged)

public class Currency:INotifyPropertyChanged
{
    public string Name { get; set; }
    public string Value { get; set; }

    public string RealValue
    {
        get { return Value; }
        set
        {
            if (true)
            {
                Value = value;
                NotifyPropertyChanged("RealValue");
            }
        }
    }
    public event PropertyChangedEventHandler? PropertyChanged;

    public override string? ToString()
    {
        return Name + " = " + Value;
    }
    public void NotifyPropertyChanged(string propName)
    {
        if (this.PropertyChanged != null)
        {
            this.PropertyChanged(this, new PropertyChangedEventArgs(propName));
        }
            
    }
}

BackgroundWorker更新代码

private void Window_ContentRendered(object sender, EventArgs e)
{
    BackgroundWorker backgroundWorker=new BackgroundWorker();
    backgroundWorker.WorkerReportsProgress = true;
    backgroundWorker.DoWork += BackgroundWorker_DoWork;
    backgroundWorker.ProgressChanged += BackgroundWorker_ProgressChanged;
    backgroundWorker.RunWorkerAsync();
}
private void BackgroundWorker_ProgressChanged(object? sender, ProgressChangedEventArgs e)
{
    List<string> list = e.UserState as List<string>;
    (lst.Items[0] as Currency).RealValue = list[0];
    (lst.Items[1] as Currency).RealValue = list[1];
    lst.Items.Refresh();
}
private void BackgroundWorker_DoWork(object? sender, DoWorkEventArgs e)
{
    WebClient webClient = new WebClient();
    while (true)
    {
        string data1 = webClient.DownloadString("https://min-api.cryptocompare.com/data/price?fsym=sol&tsyms=USD");
        string data2 = webClient.DownloadString("https://min-api.cryptocompare.com/data/price?fsym=eth&tsyms=USD");
        HtmlDocument htmlDocument1 = new HtmlDocument();
        HtmlDocument htmlDocument2 = new HtmlDocument();
        htmlDocument1.LoadHtml(data1);
        List<string> list=new List<string>() {data1,data2};
        (sender as BackgroundWorker).ReportProgress(0,list);
        Thread.Sleep(100);
    }
}

XAML代码

<Window x:Class="WpfTutorialSamples.ListView_control.FilteringSample"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="FilteringSample" Height="200" Width="300" Background="Transparent" ContentRendered="Window_ContentRendered"
    SizeChanged="Window_SizeChanged">
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <ListView x:Name="lst" ScrollViewer.HorizontalScrollBarVisibility="Hidden" SelectionChanged="lst_SelectionChanged">
        <ListView.Resources>
            <Style TargetType="ListView">
                <Setter Property="Background">
                    <Setter.Value>
                        <LinearGradientBrush>
                            <GradientStop Color="HotPink" Offset="0"/>
                            <GradientStop Color="CadetBlue" Offset="0.5"/>
                            <GradientStop Color="BlanchedAlmond" Offset="1"/>
                        </LinearGradientBrush>
                    </Setter.Value>
                </Setter>
            </Style>
        </ListView.Resources>
        <ListView.View>
            <GridView AllowsColumnReorder="False" x:Name="grd">
                <GridView.ColumnHeaderContainerStyle>
                    <Style TargetType="{x:Type GridViewColumnHeader}">
                        <Setter Property="Foreground" Value="Purple"/>
                        <Setter Property="FontWeight" Value="ExtraBold"/>
                        <Setter Property="FontSize" Value="15"/>
                        <Setter Property="IsHitTestVisible" Value="False"/>
                    </Style>
                </GridView.ColumnHeaderContainerStyle>
                <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}" Width="150"/>
                <GridViewColumn Header="Value" DisplayMemberBinding="{Binding Value}" Width="Auto"/>
            </GridView>
        </ListView.View>
    </ListView>
    <Grid Background="Aqua" Grid.Row="1">
        <TextBlock x:Name="txt" Grid.Row="1" VerticalAlignment="Center" HorizontalAlignment="Center" TextWrapping="Wrap"/>
    </Grid>
</Grid>
</Window>

问题解决说明

编辑:我已通过修改Currency类解决了问题。


内容的提问来源于stack exchange,提问作者blockchainlover

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 20:35:16