Observable collection bind to specific item (by property value)

a 夏天 提交于 2019-12-13 11:17:01

问题


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



来源:https://stackoverflow.com/questions/45818244/observable-collection-bind-to-specific-item-by-property-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!