Safe Safe - 6 days ago 5
C# Question

WPF, Binding Programmatically an item of a Observable collection of list

I have a

ObservableCollection<List<MessageView>>
(MessageView is a custom class) I instantiate it that way

public ObservableCollection<List<MessageView>> _messagesView;
public ObservableCollection<List<MessageView>> messagesView {
get {
if (_messagesView == null) {
_messagesView = new ObservableCollection<List<MessageView>>();
}
return _messagesView;
}
set {
if (_messagesView != value) {
_messagesView = value;
PropertyChanged(this, new PropertyChangedEventArgs(nameof(messagesView)));
}
}
}


This property is set on a Singleton

I want to bind one of the item collection to a datagrid it would look that way in xaml:

<xmlns:module="clr-namespace:Myproject.MyNameSpace;assembly=Myproject">
<DataGrid
Name="DataGrid_messages"
...
ItemsSource="{Binding messagesView[2], Source={x:Static module:Singleton.Instance}}"
>


This is working well that way but this is not what I want to do. I want to have the control of my index. So I have to do the binding in c# with my controller but I never found an example to bind with a special index.

Binding myBinding = new Binding("messagesView");
myBinding.Source = Singleton.Instance;
myBinding.Path = ??
DataGrid_messages.SetBinding(DataGrid.ItemsSourceProperty, myBinding);


Share your thought about this, is it possible? Or a better way to do it?

Answer

Provided that the index is fixed, creating the binding path in code behind could look like this:

myBinding.Path = new PropertyPath(string.Format("messagesView[{0}]", index));