datagrid的列并不在可视化树上,所以用需要下面的办法中转一下
public class BindingProxy : Freezable
{
protected override Freezable CreateInstanceCore()
{
return new BindingProxy();
}
public object ProxyData
{
get { return (object)GetValue(ProxyDataProperty); }
set { SetValue(ProxyDataProperty, value); }
}
public static readonly DependencyProperty ProxyDataProperty =
DependencyProperty.Register("ProxyData", typeof(object), typeof(BindingProxy));
}
view中的resources中添加:
<vm:BindingProxy x:Key="proxy" ProxyData="{Binding}" />
datagrid列定义:
<DataGridTemplateColumn Width="50" Header="SubSpec" Visibility="{Binding ProxyData.ShowAlarmSubSpec, Source={StaticResource proxy},Converter={StaticResource BooleanToVisibilityConverter}}">
viewmodel:
private bool showAlarmSubSpec;
public bool ShowAlarmSubSpec
{
get
{
return showAlarmSubSpec;
}
set
{
showAlarmSubSpec = value;
RaisePropertyChanged("ShowAlarmSubSpec");
}
}
Converter:
[ValueConversion(typeof(bool), typeof(Visibility))]
public class BooleanToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is bool)
{
return ((bool)value) ? Visibility.Visible : Visibility.Collapsed;
}
else
return Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is Visibility)
{
return (Visibility)value == Visibility.Visible;
}
return false;
}
}