[英]MVVM Datagrid to Observable Collection binding of generic types
I have a xaml UserControl in which the DataContext refers to a "Control"-ViewModel. 我有一个xaml UserControl,其中DataContext引用了“ Control” -ViewModel。
mc:Ignorable="d" d:DataContext="{d:DesignInstance controls:ControlViewModel}"
Furthermore, I´ve binded the ItemsSource to an ObservableCollection which is generic from a "Data"-ViewModel. 此外,我已将ItemsSource绑定到ObservableCollection,后者是“ Data” -ViewModel的通用类。 (Please Note: these data are only for demonstration) (请注意:这些数据仅用于演示)
<DataGrid ItemsSource="{Binding DataCollection}" SelectedItem="{Binding SelectedData}">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
<DataGridTextColumn Header="Age" Visibility="{Binding AgeVisibility}" Binding="{Binding Age}"/>
</DataGrid.Columns>
</DataGrid>
public class ControlViewModel
{
private ObservableCollection<DataViewModel> _dataViewModels;
public ObservableCollection<DataViewModel> DataViewModels
{
get { return _dataViewModels; }
set
{
_dataViewModels = value;
RaisePropertyChanged("DataViewModels");
}
}
}
The "Data"-ViewModel has the following Properties, which I´ve binded to the specific DataGridTextColumn (as you can see). “数据” -ViewModel具有以下属性,我已将它们绑定到特定的DataGridTextColumn(如您所见)。
public class DataViewModel
{
private string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
RaisePropertyChanged("Name");
}
}
private int _age;
public int Age
{
get { return _age; }
set
{
_age = value;
RaisePropertyChanged("Age");
}
}
private Visibility _ageVisibility;
public Visibility AgeVisibility
{
get { return _ageVisibility; }
}
}
Everything works, expect that the Visibilty Property of the "Age" Column doesn´t easily refer to the generic DataViewModel (Properties) of the Observable Collection such as the Binding Property. 一切正常,希望“年龄”(Age)列的Visibilty属性不会轻易引用Observable集合的通用DataViewModel(属性),例如Binding属性。 So it cannot be solved and it´s always on it´s default. 因此无法解决,并且始终处于默认状态。
If you want a bindable property then add a second RaisePropertyChanged
to the properties that control the readonly property. 如果您想要一个可绑定的属性,则将第二个RaisePropertyChanged
添加到控制readonly属性的属性中。
public class DataViewModel
{
//other stuff
private int _age;
public int Age
{
get { return _age; }
set
{
_age = value;
RaisePropertyChanged("Age");
RaisePropertyChanged("AgeVisibility");
}
}
public Visibility AgeVisibility
{
get { return this.Age > 0 ? Visibility.Visible : Visibility.Hidden; }
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.