Observable collection bind to specific item (by pr

2019-09-22 01:19发布

问题:

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.

回答1:

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.



回答2:

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