Lets say that you want to bind data based on one UI control, how would we go about doing it? I attempted one solution. First lets see how the output look like
As you can see it has a grid with 10 data items. At the bottom there is a label and text block, the text block shows how many items are in the grid. Also there is a filter button. Every time you press filter button, it will filter all the items in age increment of 20. So if I press filter then the result would be like the following
There is not data since the filter will look for age < 20. Now filter again
Now there will be 2 items, where age is less than 40 and so on. The point we are interested in is the Total rows, as the number of rows changes the grid, the number also changes. Lets look the XAML how it is done.
XAML:
1: <Grid x:Name="LayoutRoot" Background="White">
2: <sdk:DataGrid AutoGenerateColumns="true" Height="156" HorizontalAlignment="Left" Margin="35,24,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="285" />
3: <TextBlock Height="23" HorizontalAlignment="Left" Margin="190,214,0,0" Name="textBlock1" Text="{Binding ElementName=dataGrid1, Path=ItemsSource.Count}" VerticalAlignment="Top" Width="96" />
4: <Button Content="Filter" Height="23" HorizontalAlignment="Left" Margin="313,214,0,0" Name="Button" VerticalAlignment="Top" Width="75" Click="button1_Click" />
5: <sdk:Label Height="28" HorizontalAlignment="Left" Margin="35,209,0,0" Name="label1" Content="Total Rows" VerticalAlignment="Top" Width="133" />
6: </Grid>
The line we are interested in is line (3), look at the Text binding for text block. Here we say, we are want the source of data binding will be the data grid and, I am interested in total count of items source.
Lets look at the code behind on how the data binding happens and how filtering happens.
Code behind:
public partial class MainPage : UserControl
{
PagedCollectionView peopleCollection;
List<Person> people;
private int personNumber=1;
public MainPage()
{
InitializeComponent();
people = new List<Person>();
for(int i=0;i<10;i++)
people.Add(new Person() { Name = i.ToString(), Age = 20 + i * 10 });
peopleCollection = new PagedCollectionView(people);
dataGrid1.ItemsSource = peopleCollection;
}
private void button1_Click(object sender, RoutedEventArgs e)
{
peopleCollection.Filter = null;
peopleCollection.Filter = (p => ((Person)p).Age < (personNumber * 20));
personNumber++;
}
}
The code is simple and straight forward. I create a person collection and then converted it to PagedCollectionView and bind it to the grid. When user clicks Filter button, I clear the filter first then apply filter. There is no code in code behind which changes the text block count. It is all done in the XAML with stright control binding.
0 comments:
Post a Comment