Julio Kuplinsky
Julio Kuplinsky

Reputation: 41

WPF Binding in code

In order to display a data table in a ListView I have

<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 .......

with resource

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

and code behind

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

=====

Now, if I want to display one of several possible tables, I'd like to bind in code, so I have

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

but I can't figure out how to attach the TextBox to one of the GridViewColumn(s).

Any thoughts?

Thanks

Upvotes: 4

Views: 8641

Answers (1)

punker76
punker76

Reputation: 14621

here is a dynamic genration solution, that i found at the internet, and it works great.

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}}">

hope this helps

Upvotes: 3

Related Questions