A Dictionary
is not optimal for binding, since the KeyValuePair
it returns is immutable (and hence can not be used in a two-way binding).
If you still want to keep the data in a dictionary, you could wrap it in a class that contains the key (to have something to display in the TextBlock
). One way of doing it:
// some classes to represent our settings
public abstract class Parameter
{
public string Key { get; private set; }
public Parameter( string key ) { this.Key = key; }
}
public class StringParameter : Parameter
{
public string Value { get; set; }
public StringParameter( string key, string value ) : base( key )
{
this.Value = value;
}
}
Some test data:
public Dictionary<string, Parameter> m_Settings = new Dictionary<string, Parameter>();
// NOTE: we're returning the dictionary values here only
public IEnumerable<Parameter> Settings { get { return m_Settings.Values; } }
...
var p1 = new StringParameter( "Parameter 1", "Value 1" );
var p2 = new StringParameter( "Parameter 2", "Value 2" );
var p3 = new StringParameter( "Parameter 3", "Value 3" );
m_Settings.Add( p1.Key, p1 );
m_Settings.Add( p2.Key, p2 );
m_Settings.Add( p3.Key, p3 );
And a very simple UI:
<Window ...
xmlns:self="clr-namespace:WpfApplication8"
DataContext="{Binding RelativeSource={RelativeSource Self}}" >
<ItemsControl ItemsSource="{Binding Settings}">
<ItemsControl.Resources>
<DataTemplate DataType="{x:Type self:StringParameter}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Key}"/>
<TextBox Text="{Binding Value, Mode=TwoWay}"/>
</StackPanel>
</DataTemplate>
</ItemsControl.Resources>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Vertical"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</Window>
Having a generic base Parameter
allows you to have different types of settings, all with their own DataTemplate
. Note that all this lacks any validation and all that stuff you'll need as well.