Search code examples
mvvmwpfdatagrid

Datagrid not updating, Visibility property on datagridtextcolumn


So As you can see the ID column should be hidden but its not. And the debugger is showing the value of IDVisible in the xaml file to be "Hidden" but it never makes it to the window. I am calling a property changed method as well. What am I doing wrong, the ID column should disappear or at least that's what I am trying to do.

MainWindow.xaml

And here is the code for MainWindowViewModel.cs

namespace MagicDB
{
class MainWindowViewModel : ObservableObject
{
    private CardDB _cards;
    private Command _InitCardDB;
    private Visibility _IDVisible;

    public CardDB Cards
    {
        get { return _cards; }
        set { _cards = value; OnPropertyChanged("Cards"); }
    }

    public Visibility IDVisible
    {
        get { return _IDVisible; }
        set { _IDVisible = value; VerifyPropertyName("IDVisible"); OnPropertyChanged("IDVisible"); }
    }

   public MainWindowViewModel()
    {
        IDVisible = Visibility.Hidden;
        _InitCardDB = new Command(InitDB, true);
        Cards = new CardDB();
    }

And the xaml file....

<Window x:Class="WpfDataGrid.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Width="500" Height="500">
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="50" />
        <RowDefinition Height="450*" />
    </Grid.RowDefinitions>
    <DataGrid AutoGenerateColumns="False" 
        HorizontalAlignment="Left" 
        Name="dataGrid1" 
        VerticalAlignment="Top" 
        ItemsSource="{Binding Cards.cardDB}"
        CanUserReorderColumns="True"
              CanUserResizeColumns="True"
              CanUserResizeRows="False"
              CanUserSortColumns="True"
              AlternatingRowBackground="LightBlue"
              Width="480" Height="auto" Grid.Row="1" IsSynchronizedWithCurrentItem="True"  
              >
        <DataGrid.Columns>
            <DataGridTextColumn Header="ID" Binding="{Binding CardID}" Width="25" Visibility="{Binding IDVisible,Mode=TwoWay}"></DataGridTextColumn>

Solution

  • I would check your Visible binding as it is most likely failing. This page explains a few methods that you can use. I personally prefer adjusting the trace level.

    I believe the reason that the binding is failing is due to the fact that your DataContext (I assume you have set it somewhere) isn't getting to the DataGrid's columns themselves. This page explains a fix that I have used in the past to solve this problem. I think I originally found that article from this page that has several other good to know WPF 'Gotchas'.