2012-11-08 50 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

相關問題