-1

I have a question about binding a specific observable (or list) item to a textblock in my wpf application. Normally, you can bind a specific item like this

But when your collection grows to (for example) a huge collection. Binding properties like:

Mycollection[14224].Name 

Wil just become a mess. So is there an alternative binding method, that still lets me bind to a specific item in my observable collection. But does not do so by the index of the item in the collection. If so, how is this done?

Just for extra clearity:

(in 'semi' pseudo)

Public class symbol
{
   Public string Name {get; set;}
   Public string Value {get; set;}

   Public symbol(string name, string value)
   {
       this.Name = name;
       this.Value = value;
   }
}

Public class viewmodel : BaseViewModel
{

Public ObservableCollection<Symbol> Symbols{get;set;}

Public viewmodel()
{
Symbols = new ObservableCollection<Symbol>();
Symbols.Add(new symbol("a","a"));
Symbols.Add(new symbol("b","b"));
//..etc etc..

}

}

code behind:

DataContext = new viewmodel();

in xaml:

<TextBlock Text="{Binding Symbols[0].Value, Mode=TwoWay}"></TextBlock>

What i want is, to bind to the value of a symbol in this collection. but to do this by its name (the string property name).Something like:

<Textblock Text="Binding Symbols.a.Value, Mode=TwoWay}"></Textblock>

Ofcourse the binding above does not work, but its just to show you guys what im looking for.

Bart Teunissen
  • 1,420
  • 5
  • 20
  • 43
  • 4
    I cannot imagine a case when binding `Mycollection[14224]` can occur. for collections wpf has `ItemsControl` – ASh Aug 22 '17 at 13:00
  • 4
    If there are special magic items in your collection that you need to bind to individually, your viewmodel should expose them as single properties. If you are copying and pasting 14,224 TextBlocks in your XAML, you need to take ASh's advice and use an ItemsControl. – 15ee8f99-57ff-4f92-890c-b56153 Aug 22 '17 at 13:22

2 Answers2

1

Why not write an IValueConverter and give it the criteria (e.g. Name) as a parameter.

Basic Tutorial can be found here

How to pass Parameters is here

lightlike
  • 152
  • 2
  • 17
0

If you bind to a Dictionary<string, string> you could specify the string key in the XAML as I suggested here:

XAML: Bind IsChecked to list object using an enum to index

You cannot do this with an ObservableCollection<Symbol> though. And the key must be a compile-time constant. It cannot be a dynamic value that you try to resolve using a binding or something. This is not supported in XAML.

mm8
  • 163,881
  • 10
  • 57
  • 88