您可以创建一个PropertyWrapper类,并在您的窗口代码后面公开一个返回List<PropertyWrapper>
的属性并将您的ListBox.ItemsSource绑定到它。
public class PropertyWrapper
{
private readonly object target;
private readonly PropertyInfo property;
public PropertyWrapper(object target, PropertyInfo property)
{
this.target = target;
this.property = property;
}
public bool Value
{
get
{
return (bool) property.GetValue(target, null);
}
set
{
property.SetValue(target, value, null);
}
}
public PropertyInfo Property
{
get
{
return this.property;
}
}
}
你的窗口后面的代码:
public partial class Window1 : Window, INotifyPropertyChanged
{
public Window1()
{
InitializeComponent();
properties = new List<PropertyWrapper>
{
new PropertyWrapper(this, typeof(Window1).GetProperty("A")),
new PropertyWrapper(this, typeof(Window1).GetProperty("B")),
};
this.DataContext = this;
}
private List<PropertyWrapper> properties;
public List<PropertyWrapper> Properties
{
get { return properties; }
}
private bool a;
private bool b = true;
public bool A
{
get
{
return a;
}
set
{
if (value != a)
{
a = value;
NotifyPropertyChange("A");
}
}
}
public bool B
{
get
{
return b;
}
set
{
if (value != b)
{
b = value;
NotifyPropertyChange("B");
}
}
}
protected void NotifyPropertyChange(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged.Invoke(
this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
你的窗口标记:
<ListBox ItemsSource="{Binding Path=Properties}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=Property.Name}"/>
<CheckBox IsChecked="{Binding Path=Value}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
希望这有助于
这是一个有趣的解决方案,将属性从一个Class转换为一个列表,我可以用这种方式尝试,因为这更像是我想要的解决方案 - 基本上,我手动构建列表并绑定到每个列表项的每个属性,尽管它起作用,但这个解决方案可能更有用,因为我有很多属性可以绑定。 – RoguePlanetoid 2009-09-03 08:39:04
另外,如果您想要添加不同类型的属性,您可以用容器控件替换CheckBox,并使用按类型绑定的dataTemplate,并为每种类型添加数据模板(使用复选框编辑布尔值,一个文本框等)。如果你需要这个让我知道,我会为你写一个例子。 – 2009-09-03 13:54:48