一個選項:自動換行的PropertyInfo在PropertyInfoViewModel這樣你就可以綁定到它的價值:
class PropertyInfoViewModel
{
Object CRUDObject { get; set; }
PropertyInfo PropertyInfo { get; set; }
Object Value {
get
{
return PropertyInfo.GetValue(CRUDObject);
}
set
{
PropertyInfo.SetValue(CRUDObject, value);
}
}
}
你可以有一個ObservableCollection在CRUDObjectViewModel,當您創建或更改的CRUD填充它附加到(查看反射,如果被這個困惑)。
使用模板選擇器選擇一個特定的編輯器顯示爲PropertyInfoViewModel:
public class PropertyTypeTemplateSelector : DataTemplateSelector
{
public DataTemplate BooleanTemplate { get; set; }
public DataTemplate GuidTemplate { get; set; }
public DataTemplate StringTemplate { get; set; }
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
PropertyInfo propertyInfo = (item as PropertyInfoViewModel).PropertyInfo;
if (propertyInfo.PropertyType == typeof(Boolean))
{
return BooleanTemplate;
}
else if (propertyInfo.PropertyType == typeof(Guid))
{
return GuidTemplate;
}
else if (propertyInfo.PropertyType == typeof(String))
{
return StringTemplate;
}
return null;
}
}
你可以使用這樣的:
<ListBox ItemsSource="{Binding Properties}">
<ListBox.Resources>
<DataTemplate x:Key="BooleanTemplate">
<CheckBox Content="{Binding PropertyInfo.Name}" IsChecked="{Binding Value}"/>
</DataTemplate>
<DataTemplate x:Key="GuidTemplate">
<StackPanel>
<TextBox Text="{Binding PropertyInfo.Name}"/>
<TextBox Text="{Binding Value, ValueConverter={StaticResources MyGuidConverter}}"/>
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="StringTemplate">
<StackPanel>
<TextBox Text="{Binding PropertyInfo.Name}"/>
<TextBox Text="{Binding Value}"/>
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="Null"/>
</ListBox.Resources>
<ListBox.ItemTemplateSelector>
<helpers:PropertyTypeTemplateSelector BooleanTemplate="{StaticResource BooleanTemplate}"
GuidTemplate="{StaticResource GuidTemplate}"
StringTemplate="{StaticResource StringTemplate}"/>
</ListBox.ItemTemplateSelector>
</ListBox>
可能要思考如何應對變化/更新,因爲這不是使用NotifyPropertyChanged保持UI最新。
我還沒有測試過任何這個,但它應該工作,我想。
來源
2016-06-30 16:23:02
Joe
你會如何「給」對象到你的程序? – Clemens
我已投票結束這個問題「太廣泛」。但是,您始終可以設置或綁定ListBox的DisplayMemberPath屬性。 – Clemens
MVVM中的代碼完全正確。它應該只關注UI邏輯。在這種情況下,我建議你從許多第三方控制供應商/開源項目中的一個獲取「Property Editor」控件。屬性編輯器需要一個對象並創建UI以編輯其上的屬性值。這是一種常見的模式,但沒有一種可以嵌入到WPF中。 – Will