仅当对象属性为true时才绑定DataGridColumn

时间:2018-10-31 10:44:52

标签: c# wpf binding visibility datagridcolumn

我目前在尝试在WPF中进行条件绑定时遇到问题。我已经阅读了该问题,似乎“可见性”并不是DataGridColumns的真正选择,因为它不在逻辑树视图中。 我目前有一个对象“ Device”,其中包含对象“ Channel”的列表。这些通道可以是输入或输出,表示为布尔“ isInput”。我要完成的工作是创建两个数据网格,一个带有输入,一个带有输出。

<DataGrid Grid.Row="0" AutoGenerateColumns="False" ItemsSource="{Binding Path=Channels}">
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding Path=Type}" 
             Visibility="{Binding Path=(model:Channel.IsInput), 
             Converter={StaticResource BooltoVisibilityConverter}}"/>
        </DataGrid.Columns>
</DataGrid>

这是我目前拥有的,但是由于可见性似乎不起作用,所以我想采用一种方法在IsInput = false时隐藏整个行或完全跳过它。

1 个答案:

答案 0 :(得分:2)

如果需要多个网格,则需要根据需要过滤多个项目集合。

对于您的需求,假设通道对象的总数相对较小,我会做类似的事情。

public class ViewModel: ViewModelBase
{
    public ViewModel()
    {
        AllChannels = new ObservableCollection<Channel>();
        AllChannels.CollectionChanged += (s,e) =>
           { 
               RaisePropertyChanged(nameof(InputChannels));
               RaisePropertyChanged(nameof(OutputChannels));
           }
    }

    private ObservableCollection<Channel> AllChanels { get; }

    public IEnumerable<Channel> InputChannels => AllChannels.Where(c => c.IsInput);
    public IEnumerable<Channel> OutputChannels => AllChannels.Where(c => !c.IsInput);

    public void AddChannel(Channel channel)
    {
        AllChannels.Add(channel);
    }
}        

您现在可以创建两个网格控件,并将其ItemsSource属性绑定到InputChannels和OutputChannels。

相关问题