采用常规的绑定方式,是无法直接对DataGridTemplateColumn的Visibility属性进行绑定的,直接无效,查了一些资料,原因是由于Column集合只是DataGrid的一个属性,这个集合在逻辑树或者视觉树中是看不到的,也不会继承DataContext属性。
1,解决办法是先建立一个Converter类,继承IValueConverter。在这里我于外又做了个简易的封装,创建一个BaseValueConverter<T>类,继承MarkupExtension类,及IValueConverter接口
/// <summary> /// A base value converter that allows direct XAML usage /// </summary> /// <typeparam name="T">The type of this value converter</typeparam> public abstract class BaseValueConverter<T>:MarkupExtension,IValueConverter where T :class,new() { #region Markup Extension Methods /// <summary> /// Provides a static instance of the value converter /// </summary> /// <param name="serviceProvider">the service provider</param> /// <returns></returns> public override object ProvideValue(IServiceProvider serviceProvider) { return mConverter ?? (mConverter = new T()); } #endregion #region Private Members /// <summary> ///A single static instance of this value converter /// </summary> private static T mConverter = null; #endregion #region Value Converter Methods /// <summary> /// The method to convert one type to another /// </summary> /// <param name="value"></param> /// <param name="targetType"></param> /// <param name="parameter"></param> /// <param name="culture"></param> /// <returns></returns> public abstract object Convert(object value, Type targetType, object parameter, CultureInfo culture); /// <summary> /// The method to convert a value back to it's source type /// </summary> /// <param name="value"></param> /// <param name="targetType"></param> /// <param name="parameter"></param> /// <param name="culture"></param> /// <returns></returns> public abstract object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture); #endregion }
public class BooleanToVisibilityConverter:BaseValueConverter<BooleanToVisibilityConverter> { public override object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if(parameter == null) return (bool)value ? Visibility.Hidden : Visibility.Visible; else return (bool) value ? Visibility.Visible : Visibility.Hidden; } public override object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } }
2,View 引入Converter 所在的命名空间
xmlns:valueConverters="XXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
3.DataGridTemplateColumn的Visibility属性进行绑定,通过一个CheckBox的IsChecked属性来控制
<CheckBox x:Name="cboxShowControl" Content="控制DatagridColumn显隐"> <DataGridTemplateColumn Header="Test" Width="150" Visibility="{Binding Source={x:Reference cboxShowControl},Path=IsChecked,Converter={valueConverters:BooleanToVisibilityConverter}}">
在这里我的起名,BooleanToVisibilityConverter 与System的一致了。注意一下吧