Dictionary 不是最佳绑定,因为它返回的 KeyValuePair 是不可变的(因此不能用于双向绑定)。
如果您仍想将数据保存在字典中,可以将其包装在包含键的类中(以便在TextBlock 中显示一些内容)。一种方法:
// 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;
}
}
一些测试数据:
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 );
还有一个非常简单的用户界面:
<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>
拥有通用基础Parameter 允许您拥有不同类型的设置,所有设置都有自己的DataTemplate。请注意,所有这些都缺乏任何验证以及您需要的所有东西。