2012-11-08 118 views
1

我想显示一个有两列的网格 - 名称和进度。名称应该是一个字符串,进度是一个介于0.00和1.00之间的百分比值。我希望百分比显示为进度栏或类似的内容。WPF绑定到ObservableCollection - 控制行?

我在我的窗口中有一个DataGrid,创建一个简单的类与一个双和文件名。我的主要代码保持此:

public ObservableCollection<DownloadFile> files = new ObservableCollection<DownloadFile>(); 

我然后设置ItemsSource到此集合,自动生成列设置为true。它到目前为止工作得很好,包括更新。

现在,类中的double值是介于0和1之间的值的百分比。由于没有进度条,我决定,我可能会改变相应行的背景颜色,就像这样:

row.cell.Style.Background = new LinearGradientBrush(
    Brushes.Green.Color, 
    Brushes.White.Color, 
    new Point(percentage, 0.5), 
    new Point(percentage + 0.1, 0.5)); 

有没有办法以某种方式..控制哪些网格显示?现在,我被这些差异所淹没,或者DataGrid从旧的DataGridView中退步了一大步,但这并不是很好。但是这似乎完全受限于我无法轻易手动更改的一些真实数据。

回答

2

如果知道列数及其类型,最好明确地创建它们,并将AutoGenerateColumns设置为false。第一个将是一个DataGridTextColumn,对于第二个,我们要创建一个自定义模板:

<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding FilesDownloading}"> 
    <DataGrid.Columns> 
     <DataGridTextColumn Header="File" Binding="{Binding Name}"/> 
     <DataGridTemplateColumn Header="Progress"> 
      <DataGridTemplateColumn.CellTemplate> 
       <DataTemplate> 
        <ProgressBar Minimum="0" Maximum="1" Value="{Binding Progress}"/> 
       </DataTemplate> 
      </DataGridTemplateColumn.CellTemplate> 
     </DataGridTemplateColumn> 
    </DataGrid.Columns> 
</DataGrid> 

好像你将更新进步为文件下载,所以你需要你的DownloadFile类实现INotifyPropertyChanged接口。此外,这使得下载完成时发送消息变得容易:

public class DownloadFileInfo : INotifyPropertyChanged 
{ 
    public string Name { get; set; } 

    private double _progress; 
    public double Progress 
    { 
     get { return _progress; } 
     set 
     { 
      _progress = value; 
      RaisePropertyChanged("Progress"); 
     } 
    } 

    public event PropertyChangedEventHandler PropertyChanged; 
    private void RaisePropertyChanged(string propertyName) 
    { 
     if (PropertyChanged != null) 
      PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
    } 
} 
+0

不错,它的工作原理!非常感谢,看起来我真的必须仔细观察整个XAML结构! – Eisenhorn

相关问题