Reputation: 6234
I'd like to bind dictionary's item using variable as a key, for example:
PanelNames.cs
public static class PanelNames
{
public static string Panel1 = "Panel1";
public static string Panel2 = "Panel2";
}
MainWindowVM.cs
IDictionary<string, object> Panels { get; }
MainWindow.xaml
<TextBlock Content="{Binding Panels[Panel1]}" /> <-- this works fine, because Panel1 is simply string
<TextBlock Content="{Binding Panels[PanelNames.Panel1]}" /> <-- this doesn't work, because there is no key with such name, but I want to keep names outside XAML file and use PanelNames static class.
Is this possible to access Dictionary element using variable as a key in XAML? I saw this post, but it doesn't meet my requirements.
Upvotes: 2
Views: 1837
Reputation: 7277
Instead of hardcoding a string in the XAML, you should bind this to another property:
View
<TextBlock Content="{Binding PanelValue}" />
ViewModel
IDictionary<string, object> Panels { get; }
private string _panelValue;
public string PanelValue
{
get { return Panels[_panelValue]; }
set
{
// Make sure Panels has this key,
_panelValue = value;
OnPropertyChanged(nameof(PanelValue));
}
}
So in your code, you can set PanelValue
to the key whose value you want to display in the TextBlock.
Upvotes: 2