Search code examples
c#wpfxamlcollectionviewsource

C# WPF DataTable into a CollectionViewSource use that for a ViewList


I'm have gotten data from a database, now I want to put into a CollectionViewSource and then use that as the source for a ListView. I want to do this so I can filter the ListView. However I don't understand how pass the Datatable from c# to the XAML CollectionViewSource?

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

<ListView x:Name="listView" ...
          ItemsSource="{Binding Source={StaticResource NamesOfCompany}}" >
    <ListView.View>
        <GridView>
            <GridViewColumn Header="CompanyName" 
                DisplayMemberBinding="{Binding CompanyName}" />
        </GridView>
   </ListView.View>
</ListView>

<Grid Margin="2,441.5,-2,0" Grid.Row="1" >
   <TextBox x:Name="txt_search" Height="22" TextWrapping="Wrap" Text="{Binding TextSearch,UpdateSourceTrigger=PropertyChanged}" Width="234" Margin="0,0,451,8" TextChanged="txt_search_TextChanged" HorizontalAlignment="Right" VerticalAlignment="Bottom" VerticalContentAlignment="Center"/>
</Grid>

All my data from my database is held in

private DataTable dt;

I'm not sure how you assign all the data from dt into the CollectionViewSource.


Solution

  • You don't need a collectionviewsource to bind to datatable. Simply connect the datatable directly to the ItemsSource. One way to do this is in the code behind...

    DataView dv = new DataView();
    dv.Table = dt;
    dv.Filter = "CompanyName='abc'";
    listView.ItemsSource = dv;