Safe Safe - 1 year ago 174
C# Question

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

I have a

(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:

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 Source

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)); 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download