Home > Net >  How to set ListView Column Header Property IsHitTestVisible to False programatically?
How to set ListView Column Header Property IsHitTestVisible to False programatically?

Time:12-16

I am adding columns to my ListView programmaticaly with this line of code:

gridView.Columns.Add(New GridViewColumn With {.Header = myWorksheet.Cells(1, myVar).Value, .DisplayMemberBinding = New Binding(myWorksheet.Cells(1, myVar).Value)})

What I want to do is set the HitTest to False so the user cannot resize the columns that were added, I tried doing this in my XAML but it did not work:

<GridView.ColumnHeaderContainerStyle>
    <Style BasedOn="{StaticResource {x:Type GridViewColumnHeader}}" TargetType="{x:Type GridViewColumnHeader}">
        <Setter Property="IsHitTestVisible" Value="False"/>
    </Style>
</GridView.ColumnHeaderContainerStyle>

This probably requires a solution in VB.Net because the XAML code does not apply to columns created programmaticaly?


Added C# tag because I found out it can be converted to VB.Net.

CodePudding user response:

XAML style is applied to all columns added in XAML and from code behind. If you want to set IsHitTestVisible not for all, but only for some column's header, then it will be tricky.

I don't know elegant solution for it. So far I know there is no way to get easy GridViewColumnHeader object, which will be styled.

My offer would be to inject a control instead of setting header text, e.g. TextBlock, which will iterate through parents and set GridViewColumnHeader.IsHitTestVisible to false.

public class TextBlockNoHit<ParentHitTestVisibleType> : TextBlock where ParentHitTestVisibleType: UIElement 
{
    public bool lsParentHitTestVisible { get; set; }
    public TextBlockNoHit()
    {
        Loaded  = TextBlockNoHit_Loaded;
    }

    private void TextBlockNoHit_Loaded(object sender, RoutedEventArgs e)
    {
        Loaded -= TextBlockNoHit_Loaded;
                
        DependencyObject dpo = this;
        while(dpo!=null)
        {
            dpo = VisualTreeHelper.GetParent(dpo);
            if(dpo is ParentHitTestVisibleType gvch)
            {
                gvch.IsHitTestVisible = lsParentHitTestVisible;
            }
        }
    }
}

Using then:

var col = new GridViewColumn() { Header = new TextBlockNoHit<GridViewColumnHeader>() { Text = "myWorksheet.Cells...", IsHitTestVisible = false, lsParentHitTestVisible = false}, DisplayMemberBinding = new Binding("myWorksheet.Cells...") };
  • Related