2011-08-26 67 views
0

我試着去顯示一個列表框的文件的名稱和路徑。例如,名稱應該在FilePath下的Header FileName和路徑下。我不希望綁定到任何個XML,因爲我有一個代碼,以顯示文件名和size.Im新本和林不知道如何去了解這一點。謝謝!顯示從列表中的項目到列在GridView控件

+0

@fatty一切我見過迄今已綁定。我不知道如何開始也:( – puzzled

+0

你可以給我們一段代碼,你試圖將數據綁定到gridview,還有你綁定的數據中的對象的結構? – VARAK

回答

0

我不知道怎麼幫你沒有看到任何你,你正試圖將數據綁定代碼或結構的,但我給它一個鏡頭。

比方說,你要的文件名和路徑綁定在C:\ MyFolder文件目錄和您的網格視圖有一個名字grd_MyGrid:

string[] myFiles = Directory.GetFiles("C:\\MyFolder\\"); 

var files = from f in myFiles 
         select new{ 
            FileName =Path.GetFileName(f), 
            FilePath = Path.GetPathRoot(f) 
            }; 

grd_MyGrid.DataSource=files; 

爲了這個工作,你必須參考System.Linq。

希望這會有所幫助。

0

要開始爲您送行,我將提供一些代碼,但你真的應該至少對一些基本的讀了,當談到XAML和WPF爲今後的發展任務。

如果你可以不使用列表框,我會建議使用DataGrid(在.net 4.0 - 或在WPF Toolkit on CodePlex)。 DataGrid更容易在要顯示網格或報表中的數據的情況下使用。

要在XAML創建DataGrid,則可以使用下面的代碼(在.NET 4)

<DataGrid HorizontalScrollBarVisibility="Auto" ItemsSource="{Binding Path=ItemsToDisplay}" IsReadOnly="True" AutoGenerateColumns="True" /> 

這將創建一個簡單DataGrid對象爲你在屏幕上顯示。由於AutoGenerateColumns已設置爲true,你的列將是你在控制自動創建。

您也可能會注意到,我已經設置了ItemsSource屬性,這是DataGrid中會得到它的項目從屬性。

要在頁面代碼隱藏文件定義了這一點,你就可以做這樣的事情:

public System.Collections.ObjectModel.ObservableCollection<Item> ItemsToDisplay { get; private set; }

請注意,在代碼隱藏屬性的名稱是如何的名稱相匹配DataGrid上綁定的屬性。這就是視圖(頁面文件)鏈接到ViewModel(代碼隱藏)的方式

要測試它,請創建一個簡單的測試類並使用項填充ItemsToDisplay集合。

例如:

在我MainWindow.xaml.cs文件

public partial class MainWindow : Window 
{ 
    public MainWindow() 
    { 
     InitializeComponent(); 
     DataContext = this; 
     ItemsToDisplay = new System.Collections.ObjectModel.ObservableCollection<Item>(); 

     ItemsToDisplay.Add(new Item("Homer", 45)); 
     ItemsToDisplay.Add(new Item("Marge", 42)); 
     ItemsToDisplay.Add(new Item("Bart", 10)); 
     ItemsToDisplay.Add(new Item("Lisa", 8)); 
     ItemsToDisplay.Add(new Item("Maggie", 2)); 
    } 

    public System.Collections.ObjectModel.ObservableCollection<Item> ItemsToDisplay { get; private set; } 
} 

public class Item 
{ 
    public string Name { get; private set; } 
    public int Age { get; private set; } 

    public Item(string name, int age) 
    { 
     Name = name; 
     Age = age; 
    } 
} 

在我的主窗口。XAML文件:

<Window x:Class="Stackoverflow.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="350" Width="525"> 
    <Grid> 
     <DataGrid HorizontalScrollBarVisibility="Auto" ItemsSource="{Binding Path=ItemsToDisplay}" AutoGenerateColumns="True" IsReadOnly="True" /> 
    </Grid> 
</Window> 

它看起來像:

enter image description here

相關問題