I am beginner to WPF and I am facing problem while trying to bind a Dependency Property as the source of a CollectionViewSource
.
The user control exposes a DependencyProperty
of type List
. It is used to present the data in a DataGrid
with the help of CollectionViewSource
(using it for Filtering, Grouping and Sorting operations).
My MainWindow XAML
:
<Window>
<local:CustomUserControl x:Name="CustomUCDataGrid" ListToDisplay="{Binding listFromDB}"/>
<Window>
My MainWindow.cs
:
public partial class MainWindow : Window
{
public List<customType> listFromDB{get;set;}
public MainWindow{
listFromDB = GetListFromDB();
InitializeComponent();
this.DataContext = this;
}
}
CustomUserControl.xaml
looks something like:
<UserControl x:Name="ParentNode">
<DataGrid DataContext="{Binding ElementName=ParentNode}">
<StackPanel>
<DataGrid x:Name="DirectDataGrid" ItemSource="{Binding ListToDisplay}"/>
<DataGrid x:Name="DataGridWithCVS" ItemsSource="{Binding cvsList.View}"/>
</StackPanel>
</DataGrid>
</UserControl>
CustomUserControl.xaml.cs
looks like:
public partial class CustomUserControl: UserControl
{
public List<customType> ListToDisplay{
get { return (List<customType>)GetValue(ListToDisplayProperty); }
set { SetValue(ListToDisplayProperty, value); }
}
public static readonly DependencyProperty ListToDisplayProperty=
DependencyProperty.Register("ListToDisplay", typeof(List<customType>),
typeof(CustomUserControl));
public CollectionViewSource cvsList { get; set; }
public CustomUserControl{
InitializeComponent();
cvsList = new CollectionViewSource();
cvsList.Source = ListToDisplay;
DataGridWithCVS.ItemsSource = CollectionViewSource.GetDefaultView(cvsList);
}
}
Here the DataGrid with name "DirectDataGrid" has no problem in displaying the data supplied to it from the MainWindow, but the DataGrid with name "DataGridWithCVS" doesn't display any data. Couldn't find any errors while debugging.
Things I have already Tried:
<UserControl x:Name="ParentNode"> <DataGrid DataContext="{Binding ElementName=ParentNode}">...
).It's just some kind of madness :)
Leave Code Behind alone.
In your case, apart from declaring DependecyProperty, there should be nothing there.
<UserControl x:Name="ParentNode">
<UserControl.Resources>
<CollectionViewSource x:Key="cvsList"
Source="{Binding ListToDisplay, ElementName=ParentNode}"/>
</UserControl.Resources>
<StackPanel>
<DataGrid x:Name="DirectDataGrid" ItemsSource="{Binding ListToDisplay, ElementName=ParentNode}"/>
<DataGrid x:Name="DataGridWithCVS" ItemsSource="{Binding Mode=OneWay, Source={StaticResource cvsList}}"/>
</StackPanel>
</UserControl>