有没有办法根据绑定隐藏给定列。我已经尝试在DataGridTextColumn上设置visibility属性(使用正确的转换器),但这似乎不起作用。如果我直接设置值(而不是通过绑定),它就可以工作。列可见性是数据网格的全部或全部处理吗?
答案 0 :(得分:6)
你真正需要做的就是添加:
<Style x:Key="vStyle" TargetType="{x:Type DataGridCell}">
<Setter Property="Visibility" Value="{Binding YourObjectVisibilityProperty}"/>
</Style>
然后在列中使用以下内容:
<DataGridTextColumn CellStyle="{StaticResource vStyle}"/>
答案 1 :(得分:3)
看看这篇文章,问题解释了
Binding in a WPF data grid text column
在这里
http://blogs.msdn.com/b/jaimer/archive/2008/11/22/forwarding-the-datagrid-s-datacontext-to-its-columns.aspx
从第一个链接引用JaredPar
“基本上问题是DataGridTextColumn没有父级可以从中继承Binding,因为它不是逻辑树或可视树的一部分。您必须设置继承上下文才能访问绑定信息”
解决方法,以使其工作..
public class DataGridContextHelper
{
static DataGridContextHelper()
{
DependencyProperty dp = FrameworkElement.DataContextProperty.AddOwner(typeof(DataGridColumn));
FrameworkElement.DataContextProperty.OverrideMetadata(typeof(DataGrid),
new FrameworkPropertyMetadata
(null, FrameworkPropertyMetadataOptions.Inherits,
new PropertyChangedCallback(OnDataContextChanged)));
}
public static void OnDataContextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
DataGrid grid = d as DataGrid;
if (grid != null)
{
foreach (DataGridColumn col in grid.Columns)
{
col.SetValue(FrameworkElement.DataContextProperty, e.NewValue);
}
}
}
}
public partial class App : Application
{
static DataGridContextHelper dc = new DataGridContextHelper();
}
<DataGrid x:Name="c_dataGrid" AutoGenerateColumns="False" DataContext="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=SelectedItem}">
<DataGrid.Columns>
<DataGridTextColumn Visibility="{Binding Path=(FrameworkElement.DataContext), RelativeSource={x:Static RelativeSource.Self}, Converter={StaticResource HideColumnAConverter}}" />
</DataGrid.Columns>
</DataGrid>
object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
{
return Visibility.Visible;
}
// Whatever you're binding against
TestClass testClass = value as TestClass;
return testClass.ColumnAVisibility;
}