Reputation: 49
I have a couple of textboxes binded with a Dictionary
<TextBox Text="{Binding Path=MyField[NotDefinedIndex], Mode=TwoWay}"></TextBox>
and it throws a "cannot connect to index" exception if I try to use a index not defined in the data context. Is there a way to catch this error, define the index (MyFileld["NotDefinedIndex"] = string.Empty) and then complete the binding?
Is there any way to bind on indexed properties in .NET Framework?
Upvotes: 1
Views: 1189
Reputation: 25201
Hiding a binding error when you're binding to an undefined index is probably not a very good idea; however, it's possible to define a property that will access the dictionary and return string.Empty
if the value doesn't exist, so you won't get a binding error. For example, in your view model:
public Dictionary<string, string> MyField { get; set; }
public string this[string key]
{
get
{
string result;
if (MyField.TryGetValue(key, out result))
{
return result;
}
return string.Empty;
}
}
Then in XAML:
<TextBox Text="{Binding Path=[NotDefinedIndex], Mode=TwoWay}"></TextBox>
Upvotes: 1