WPF中的绑定祖先元素

时间:2019-01-15 16:22:32

标签: c# wpf

我正在通过将Visibility属性绑定到viewModel的属性来隐藏Datagrid的列。 ItemsSource工作正常,并且网格中有很多行,可以正确设置Datacontext。您能帮我解决我做错的事情吗?谢谢

<StackPanel>        
    <DataGrid ItemsSource="{Binding SortedPlanning}" IsReadOnly="True" AutoGenerateColumns="False" CanUserResizeRows="False">
    <DataGrid.Columns >
            <DataGridTextColumn Header ="NNI" Binding="{Binding SortedPlanning.Nni}" Width="80" Visibility="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type StackPanel}}, Path=ColumnVisibility}">
                <DataGridTextColumn.ElementStyle>
                    <Style>
                        <Setter Property="FrameworkElement.HorizontalAlignment" Value="Center"/>
                    </Style>
                </DataGridTextColumn.ElementStyle>
            </DataGridTextColumn>
            <DataGridTextColumn Header ="Nom" Binding="{Binding LastName}" Width="120" Visibility="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=ColumnVisibility}">
            <DataGridTextColumn.ElementStyle>
                <Style>
                    <Setter Property="FrameworkElement.HorizontalAlignment" Value="Center"/>
                </Style>
            </DataGridTextColumn.ElementStyle>
            </DataGridTextColumn>
            <DataGridTextColumn Header ="Prénom" Binding="{Binding FirstName}" Width="80" Visibility="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=ColumnVisibility}">
            <DataGridTextColumn.ElementStyle>
                <Style>
                    <Setter Property="FrameworkElement.HorizontalAlignment" Value="Center"/>
                </Style>
            </DataGridTextColumn.ElementStyle>
            </DataGridTextColumn>                
            </DataGridTextColumn>
            <DataGridTextColumn Header ="Campagne" Binding="{Binding Campaign}" Width="120">
            <DataGridTextColumn.ElementStyle>
                <Style>
                    <Setter Property="FrameworkElement.HorizontalAlignment" Value="Center"/>
                </Style>
            </DataGridTextColumn.ElementStyle>
            </DataGridTextColumn>                
</DataGrid>
</StackPanel>

查看模型:

public interface IPlanningViewModel : IDisposable
{
    ObservableCollection<PlanningEntry> SortedPlanning { get; }
    Visibility ColumnVisibility { get; }
    bool FilterGrid { get; set; }
    DateTime FromDate { get; set; }
    DateTime ToDate { get; set; }
}

我希望列“ NNI”,“ Nom”和“Prénom”绑定到VM的ColumnVisibility,但这不会发生。

1 个答案:

答案 0 :(得分:0)

您将使用以下语法。

它应该可以解决您的问题。

<DataGridTextColumn Visibility="{Binding Path=DataContext.ColumnVisibility, RelativeSource={RelativeSource AncestorType=DataGrid}}" />