我有一个xaml UserControl,其中DataContext引用“Control”-ViewModel。
mc:Ignorable="d" d:DataContext="{d:DesignInstance controls:ControlViewModel}"
此外,我已将ItemsSource绑定到一个ObservableCollection,它是一个通用的“Data”-ViewModel。 (请注意:这些数据仅用于演示)
<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");
}
}
}
“数据”-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; }
}
}
一切正常,期望“Age”列的Visibilty属性不能轻易引用Observable Collection的通用DataViewModel(Properties),例如Binding Property。所以它无法解决,它始终是默认的。
答案 0 :(得分:-1)
如果需要可绑定属性,请将第二个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; }
}
}
您还可以使用this
等类型转换器