Skip to main content
 首页 » 编程设计

C# WPF OnPropertyChanged 在 foreach 循环中

2024年02月24日17xxx_UU

我一直在努力学习和利用 WPF 和数据绑定(bind)。我有一个 ListView ,其中有一列将显示三个图像之一,如以下代码片段所示:

<GridViewColumn Header="Status" Width="50"> 
  <GridViewColumn.CellTemplate> 
    <DataTemplate> 
      <Image x:Name="TheImage" Height="18"/> 
        <DataTemplate.Triggers> 
          <DataTrigger Binding="{Binding Path=Status}" Value="queued"> 
            <Setter TargetName="TheImage" Property="Source" Value="Images\que_48.png" /> 
          </DataTrigger> 
          <DataTrigger Binding="{Binding Path=Status}" Value="completed"> 
            <Setter TargetName="TheImage" Property="Source" Value="Images\complete_48.png" /> 
          </DataTrigger> 
          <DataTrigger Binding="{Binding Path=Status}" Value="failed"> 
            <Setter TargetName="TheImage" Property="Source" Value="Images\fail_48.png" /> 
          </DataTrigger> 
        </DataTemplate.Triggers> 
      </DataTemplate> 
    </GridViewColumn.CellTemplate> 
  </GridViewColumn> 

我有一个类 (BatchQueueItem),其中包含用于处理 PropertyChange 事件的代码:

public string status; 
  public string Status 
  { 
    get { return status; } 
    set  
    {  
      status = value; 
      OnPropertyChanged("Status"); 
    }             
  } 
  // Create the OnPropertyChanged method to raise the event 
 
  public event PropertyChangedEventHandler PropertyChanged;     
  private void OnPropertyChanged(string status) 
  { 
    if (PropertyChanged != null) 
    { 
      PropertyChanged(this, new PropertyChangedEventArgs(status)); 
    } 
  } 

我在 ListView 窗口页面上有一个按钮:

private void btnStart_Click(object sender, RoutedEventArgs e) 
{ 
  foreach (var item in listView1.Items) 
  { 
    BatchQueueItem bqi = (BatchQueueItem)item; 
    string currFile = bqi.CurrFile; 
    if (mainWindow.isIsbnInFileName(ref currFile)) 
    { 
       bqi.Status = "completed"; 
    } 
    else 
    { 
      bqi.Status = "failed"; 
    } 
  } 
} 

我遇到的问题是,在 foreach 循环完成并且 btnStart_Click() 方法完成之前,图像不会更新。一旦发生这种情况,所有图像都会按预期更新,只是一次而不是迭代更新。

我想要的,也是我认为会发生的,是 foreach 循环的每次迭代都会更新相应行的图像。毫无疑问,我遗漏了一些关于这一切如何运作的重要信息。有什么建议吗?

请您参考如下方法:

The problem I am having is that the images do not update until after the foreach loop has completed and the btnStart_Click() method has completed. Once that happens, all the images update as expected, just all at once not iteratively.

What I am wanting, and what I thought would happen, was that each iteration of the foreach loop would update the corresponding row's image. Undoubtedly I am missing something important about how this all works. Any tips?

这是你如何更新的问题。

问题不在于 UI 没有更新——在内部,它确实在更新。问题是您正在主 UI 线程上执行此更新和 foreach 循环。当您执行此操作时,UI 将被完全阻塞(而不是刷新/重绘),直到您的操作 100% 完成,并且消息泵可以再次运行。

有一些选项可以解决这个问题 - 如果您的操作需要一段时间,并且您希望它在运行时更新,您可以将 foreach 循环移动到在后台线程上运行的委托(delegate)中。然后,您将使用 Dispatcher 将状态更新调用回 UI 线程。

当您有一个长时间运行的操作时,这有两个好处:

  1. 您可以在您的 UI 中获取实例反馈/状态
  2. 您的用户界面在您的操作运行时保持响应。