Today, I was working on a WPF UserControl to display the current value of a few variables. I was wondering if there would be a way to make a super simple property grid in WPF. The problem is on the starred line of the XAML below. How would I bind a string to a property with an ItemTemplate like I have setup below? To be more clear can I embed bindings inside of one another {Binding Path={Binding Value}}.
Here is the class:
public class Food
{
public string Apple { get; set; }
public string Orange { get; set; }
public IEnumerable<KeyValuePair<string, string>> Fields
{
get
{
yield return new KeyValuePair<string, string>("Apple Label", "Apple");
yield return new KeyValuePair<string, string>("Orange Label", "Orange");
}
}
}
And here is the XAML:
<UserControl x:Class="MAAD.Plugins.FRACTIL.Simulation.SimulationStateView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="331" Width="553">
<ListView ItemSource="{Binding Fields}">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Key}" />
**<TextBlock Text="{Binding Path={Binding Value}}" />**
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</UserControl>
The essence of the problem is that you need not just the list of field descriptions and names, but the actual object that has those fields and names.
You can use a converter like that adds target references to the field objects and provides a value accessor, like this:
With this converter you can bind your ItemsSource like this:
By the way, a much more efficient way to implement your Fields property is:
Though frankly I would use description attributes on the individual properties along with reflection instead of hard-coding the list. That would also eliminate the need for the MultiBinding in the first place.