所有,一个简单的问题。我有一个DataGrid
的MVVM应用程序,我已使用
<DataGrid ItemsSource="{Binding Path=Resources}" ...></DataGrid>
通过
定义Resources
public ObservableCollection<ResourceViewModel> Resources { get; private set; }
但是,在ResourceViewModel
类中,我不仅拥有我希望在DataGrid
中显示的属性,而且我不的其他属性也希望显示在DataGrid
中ResourceViewmodel
。 public class ResourceViewModel : WorkspaceViewModel, IDataErrorInfo
{
readonly Resource resource;
readonly ResourceDataRepository resourceRepository;
private bool isSelected;
public ResourceViewModel(Resource resource, ResourceDataRepository resourceRepository)
{
if (resource == null)
throw new ArgumentNullException("resource");
if (resourceRepository == null)
throw new ArgumentNullException("resourceRepository");
this.resource = resource;
this.resourceRepository = resourceRepository;
}
public string KeyIndex
{
get { return this.resource.KeyIndex; }
set
{
if (value == this.resource.KeyIndex)
return;
this.resource.KeyIndex = value;
base.OnPropertyChanged("KeyIndex");
}
}
public string FileName
{
get { return this.resource.FileName; }
set
{
if (value == this.resource.FileName)
return;
this.resource.FileName = value;
base.OnPropertyChanged("FileName");
}
}
public List<string> ResourceStringList
{
get { return this.resource.ResourceStringList; }
set
{
if (Utilities.Utilities.ScrambledEquals<string>(this.resource.ResourceStringList, value))
return;
this.resource.ResourceStringList = value;
base.OnPropertyChanged("ResourceStringList");
}
}
public bool IsSelected
{
get { return isSelected; }
set
{
if (value == isSelected)
return;
isSelected = value;
base.OnPropertyChanged("IsSelected");
}
}
}
类是
IsSelected
我不希望DataGrid
出现ResourceStringList
,我希望Datagrid
中的每个项目都显示在IsSelected
的不同列中。我的问题是:
1。如何阻止Checkbox
在DataGrid
中显示[{1}}]?
2。如何绑定DataGrid
以自动在不同的列中显示项目?
您尝试了什么:
我试图从ResourceViewmodel
类继承并绑定到它,但这很恶心,我想要另一个更优雅的解决方案;拜托:]。
我不知道如何继续这个。 List
中存储的项目数是可变的并且在运行时设置 - 因此需要List
。
一如既往,非常感谢您的时间。
答案 0 :(得分:4)
我认为选项是关闭Silvermind提到的自动生成(即将DataGrid.AutoGenerateColumns设置为false然后定义列)或实现ITypedList。例如,您可以创建一个实现ITypedList的派生ObservableCollection,并根据您要隐藏的属性上的某些属性返回属性。
public partial class MainWindow : Window
{
public MainWindow()
{
this.DataContext = new TypedListObservableCollection<Foo>();
InitializeComponent();
}
}
public class TypedListObservableCollection<T> : ObservableCollection<T>
, ITypedList
{
public TypedListObservableCollection()
{
}
PropertyDescriptorCollection ITypedList.GetItemProperties(PropertyDescriptor[] listAccessors)
{
return TypeDescriptor.GetProperties(typeof(T), new Attribute[] { BrowsableAttribute.Yes });
}
string ITypedList.GetListName(PropertyDescriptor[] listAccessors)
{
return typeof(T).Name;
}
}
public class Foo
{
public string Name
{
get;
set;
}
[Browsable(false)]
public bool IsSelected
{
get;
set;
}
}
答案 1 :(得分:1)
对我而言,更容易不自动生成列。但这是个人偏好,所以我认为不允许暴露某些属性的最简单方法是使用接口的强大功能:)