如何将 DataGridTemplateColumn.Visibility 绑定到 DataGrid.ItemsSource 之外的属性? [英] How to bind DataGridTemplateColumn.Visibility to a property outside of DataGrid.ItemsSource?

查看:25
本文介绍了如何将 DataGridTemplateColumn.Visibility 绑定到 DataGrid.ItemsSource 之外的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将 DataGridTemplateColumnVisibility 绑定到 DataGrid.ItemsSource 之外的属性,因为我需要绑定此列在 ViewModel 内的一个属性的所有行中,但据我所知,您只需将其绑定到 ItemsSource 内的某些内容,或者您​​应该使用 ElementStyleEditingElementStyle我已经试过这个代码:

I need to bind the Visibility of a DataGridTemplateColumn to a property outside of the DataGrid.ItemsSource,because i need to bind this column in the all the rows to one property inside the ViewModel,but as far as i know you just can bind that to something inside the ItemsSource or you should use ElementStyle and EditingElementStyle I've Already tried this code:

 <DataGridTemplateColumn Header="post" 
                      Visibility="{Binding DataContext.ProjectPostVisibility
                    , RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=MvvmCommonControl:DataGrid}}"/>

而且我确定我的绑定是正确的,因为当我像下面这样绑定 DataGridCell.Visibility 时它工作正常:

And i'm Sure my binding is correct because it works fine when i bind the DataGridCell.Visibility like below:

<DataGridTemplateColumn Header="post">
    <DataGridTemplateColumn.CellStyle>
                        <Style TargetType="DataGridCell">
                            <Setter Property="Visibility" Value="{Binding DataContext.ProjectPostVisibility,RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=MvvmCommonControl:DataGrid}}"/>
                        </Style>
                    </DataGridTemplateColumn.CellStyle>
</DataGridTemplateColumn >

推荐答案

您的绑定是正确的,但不能直接与 DataGridTemplateColumn 一起使用,因为它不在可视化树中.所以它不是继承 DataContext.

Your binding is correct, but it won't work with DataGridTemplateColumn directly because it's not in the visual tree. So it's not inherting DataContext.

您需要从后面的代码中绑定DataGridTemplateColumn.这里有一个演示,展示了一种方法.

You need to bind the DataGridTemplateColumn from code behind. Here is a demo that shows a way of doing it.

这篇关于如何将 DataGridTemplateColumn.Visibility 绑定到 DataGrid.ItemsSource 之外的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆