代码中的WPF绑定

时间:2011-06-16 17:46:19

标签: wpf binding

为了在ListView中显示数据表,我有

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

=====

现在,如果我想显示几个可能的表中的一个,我想绑定代码,所以我有

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

但我无法弄清楚如何将TextBox附加到其中一个GridViewColumn。

有什么想法?

由于

1 个答案:

答案 0 :(得分:3)

这是一个动态的生成解决方案,我在互联网上找到了它,效果很好。

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

希望这会有所帮助