Home > other >  C# WPF | Change DisplayMemberPath programmatically
C# WPF | Change DisplayMemberPath programmatically

Time:08-30

I have a class Person with three properties Name, LastName and FullName. I use MVVM - in the ModelView, I have a List<Person> Persons.

My view looks like this:

 <Button Content="LastName" Command="{Binding LastNameCommand, Mode=OneWay}" />
<ListView IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding Persons}">
  <ListView.View>
   <GridView>
     <GridView.Columns>
       <GridViewColumn Header="Name"
            DisplayMemberBinding="{Binding Name}" />
       <GridViewColumn Header="FullName"
            DisplayMemberBinding="{Binding FullName}" />
    </GridView.Columns>
   </GridView>
  </ListView.View>
</ListView>

My goal is now to change the part

       <GridViewColumn Header="Name"
            DisplayMemberBinding="{Binding Name}" />

to

       <GridViewColumn Header="LastName"
            DisplayMemberBinding="{Binding LastName}" />

when I click on the button.

How can I achieve that?

CodePudding user response:

Setting or changing the DisplayMemberBinding property of a GridViewColumn should be done in the view.

The view model shouldn't know or care about any DisplayMemberBinding. It only updates the source properties (Name and FullName in this case).

So hook up an event handler for the button in the view and set the view-related property there:

private void Button_Click(object sender, RoutedEventArgs e)
{
    col1.DisplayMemberBinding = new Binding("path");
}

XAML:

<Button Content="LastName" Click="Button_Click" Command="{Binding LastNameCommand, Mode=OneWay}" />
<ListView IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding Persons}">
    <ListView.View>
        <GridView>
            <GridView.Columns>
                <GridViewColumn x:Name="col1" Header="Name" DisplayMemberBinding="{Binding Name}" />
                <GridViewColumn x:Name="col2" Header="FullName" DisplayMemberBinding="{Binding FullName}" />
            </GridView.Columns>
        </GridView>
    </ListView.View>
</ListView>

This does not break the MVVM pattern in any way. Trying to modify a DisplayMemberBinding in a view model certainy does. MVVM is not about eliminating view-related code from the views. It's about separation of concerns.

  • Related