I am trying to create a user control with similar functionality, such as a DataGrid (but a DataGrid is not suitable here).
What I would like to achieve looks something like this:
<my:CustomList ItemsSource="{Binding Items}"> <my:CustomList.Columns> <my:Column Width="60" Binding="{Binding MyCustomProperty}" /> </my:CustomList.Columns> </my:CustomList>
where Elements will come from ViewModel (for example) as follows:
public ObservableCollection<Item> Items { get; set; } public class Item { public string MyCustomProperty { get; set; } public string MyAnotherCustomProperty { get; set; } }
I have a problem with binding to MyCustomProperty.
If I inherit my user control from a DataGrid and use its columns, the DataContext streams from ItemsSource to Bindings in the columns are just fine. I would like to do the same with my custom control that does not inherit from DataGrid. What is the magic of DataGrid.Columns data getting context from ItemsSource?
Edit: Let me ask about it differently:
If I implement a custom DataGridColumn
public class MyDataGridColumn : DataGridBoundColumn { private Binding _bindingSubText; public Binding BindingSubText { get { return _bindingSubText; } set { if (_bindingSubText == value) return; var oldBinding = _bindingSubText; _bindingSubText = value; OnBindingChanged(oldBinding, _bindingSubText); } } protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem) { var textTextBlock = new TextBlock(); var bindingText = Binding ?? new Binding(); textTextBlock.SetBinding(TextBlock.TextProperty, bindingText); var textSubTextBlock = new TextBlock(); var bindingSubText = BindingSubText ?? new Binding(); textSubTextBlock.SetBinding(TextBlock.TextProperty, bindingSubText); var stackPanel = new StackPanel() { Orientation = Orientation.Vertical }; stackPanel.Children.Add(textTextBlock); stackPanel.Children.Add(textSubTextBlock); return stackPanel; } protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem) {
and try using it in XAML as follows:
<DataGrid ItemsSource="{Binding Items}" AutoGenerateColumns="False"> <DataGrid.Columns> <my:MyDataGridColumn Binding="{Binding MyCustomProperty}" BindingSubText="{Binding MyAnotherCustomProperty}" /> </DataGrid.Columns> </DataGrid>
The binding for the BindingSubText property should still come with the DataContext of the DataGrid parent, offering me the elements. MyAnotherCustomProperty will have wigglies in the designer, but it will work in standby mode (due to dynamic binding). My problem is that someone else will use this custom DataGridColumn, he / she will need to know this and will have the βwrongβ IntelliSense to bind.
How is the context for the Binding DataGridColumn property set, so that IntelliSense works as expected?
c # wpf custom-controls datacontext
Janez lukan
source share