0

DataGrid 列はビジュアル ツリーの一部ではないため、列の可視性プロパティを VM のブール値プロパティに直接バインドできないことを認識しています。別の方法で行う必要があります。以下は私がやった方法です:

public class LocalVm
{
    public static ObservableCollection<Item> Items
    {
        get
        {
            return new ObservableCollection<Item>
            {
                new Item{Name="Test1", ShortDescription = "Short1"}
            };
        }
    }

    public static bool IsDetailsModeEnabled
    {
        get { return true; }
    }
}

public class Item : INotifyPropertyChanged
{
    private string _name;

    public string Name
    {
        get { return _name; }
        set
        {
            _name = value;
            OnPropertyChanged();
        }
    }


    private string _shortDescription;

    public string ShortDescription
    {
        get
        {
            return _shortDescription;
        }
        set
        {
            _shortDescription = value;
            OnPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        var handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

XAML:

<Window x:Class="Wpf.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:Wpf"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        d:DataContext="{d:DesignInstance Type=local:LocalVm}"
        Title="MainWindow" Height="350" Width="525" 
        Name="MyWindow">

    <Window.Resources>
        <BooleanToVisibilityConverter x:Key="BoolToVis" />

        <DataGridTextColumn x:Key="ThatPeskyColumn"
                            Binding="{Binding Size}" 
                            Visibility="{Binding DataContext.IsDetailsModeEnabled, 
                            Source={x:Reference MyWindow}, 
                            Converter={StaticResource BoolToVis}}"/>

    </Window.Resources>

    <Grid>
        <DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Items}">
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding Name}" />
                <StaticResource ResourceKey="ThatPeskyColumn"/>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>

ただし、私の xaml ウィンドウでは、「可視性」プロパティに「オブジェクト参照がオブジェクトのインスタンスに設定されていません」というエラーがあります。ソースとコンバーターの部分を削除すると、エラーは発生しますが、正しくバインドされません。私が間違っていることは何ですか?

前もって感謝します

4

1 に答える 1