2011-06-16 42 views
4

結合爲了在ListView顯示的數據表我有WPF在代碼

<ListView ItemsSource="{Binding Source={StaticResource AdministrationView}}" IsSynchronizedWithCurrentItem="True" Name="lvTable">     
    <ListView.ItemContainerStyle> ... stuff ... </ListView.ItemContainerStyle> 
     <ListView.View> 
      <GridView> 
       <GridViewColumn Header="Pattern"> 
        <GridViewColumn.CellTemplate> 
         <DataTemplate> 
          <TextBox Text="{Binding Path=Pattern}" /> 
         </DataTemplate> 
        </GridViewColumn.CellTemplate> 
       </GridViewColumn> 
       <GridViewColumn Header="Account"> 
        <GridViewColumn.CellTemplate> 
         <DataTemplate> 
          <TextBox Text="{Binding Path=AccountName}" /> 
    .... closing tags ....... 

與資源

<Window.Resources>  
    <CollectionViewSource x:Key="AdministrationView"/> 
</Window.Resources> 

和代碼後面

var db = new XDataContext(); 
var data = db.Translations; 
var viewSource = (CollectionViewSource)FindResource("AdministrationView"); 
viewSource.Source = data; 

=====

現在,如果我想顯示一個se veral可能的表,我想在代碼綁定,所以我有

data = .... 
var tb = new TextBox(); 
var binding = new Binding("Pattern"); 
binding.Source = db.Accounts; 
tb.SetBinding(TextBlock.TextProperty, binding); 

,但我無法弄清楚如何將文本框連接到GridViewColumn(一個或多個)之一。

有什麼想法?

謝謝

回答

3

這裏是一個動態genration解決方案,我發現在互聯網上,它工作的很棒。

public class MyListView : ListView { 
public MyListView() { 
    ItemsSourceProperty.AddOwner(typeof(MyListView), new FrameworkPropertyMetadata(null, OnItemsSourcePropertyChanged)); 
} 

private static void OnItemsSourcePropertyChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e) { 
    if (e.OldValue != e.NewValue && e.NewValue != null) { 
    var lv = (MyListView)dependencyObject; 
    var gridView = new GridView(); 
    lv.View = gridView; 
    gridView.AllowsColumnReorder = true; 
    var properties = lv.DataType.GetProperties(); 
    foreach (var pi in properties) { 
     var binding = new Binding {Path = new PropertyPath(pi.Name), Mode = BindingMode.OneWay}; 
     var gridViewColumn = new GridViewColumn() {Header = pi.Name, DisplayMemberBinding = binding}; 
     gridView.Columns.Add(gridViewColumn); 
    } 
    } 
} 

public Type DataType { get; set; } 
} 


<local:MyListView x:Name="listView" DataType="{x:Type dbTranslationsType}" 
        ItemsSource="{Binding Source={StaticResource AdministrationView}}"> 

希望這有助於