您可以創建一個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