[英]WPF binding to a property not in the DataGrid ItemSource
I am wondering how I can bind a DataGrid DataGridTemplateColumn to a property in that isn't in the DataGrid ItemSource, but the property is within the same DataContext of the Itemsource? 我想知道如何将DataGrid DataGridTemplateColumn绑定到不在DataGrid ItemSource中的属性,但是该属性在ItemSource的同一DataContext中?
XAML XAML
// I am trying to bind the Visibility property to a property called Visible
<DataGridTemplateColumn Header="Apply" Visibility="{Binding source Visible}">
// However the visible property doesnt exist inside the resource cvsCustomers
ItemsSource="{Binding Source={StaticResource CustomerCollection}}"
C# C#
// But they both live in the same ViewModel i.e. DataContext
private Visibility m_Visible = Visibility.Hidden;
public Visibility Visible
{
get { return m_Visible; }
set { m_Visible = value; }
}
private ObservableCollection<Customer> m_CustomerCollection = null;
public ObservableCollection<Customer> CustomerCollection
{
get { return m_CustomerCollection; }
set { m_CustomerCollection = value; }
}
Can this be achieved? 能做到吗?
Thanks 谢谢
Datagrid columns does not comes under the visual tree of the DataGrid
. Datagrid列不在
DataGrid
的可视树下。 hence you will need to use the BindingProxy to make ViewModel accessible to your DataGridTemplateColumn
. 因此,你将需要使用BindingProxy使视图模型访问您的
DataGridTemplateColumn
。 I have explained how to create and use BindingProxy
in the answer below: 我已经在下面的答案中解释了如何创建和使用
BindingProxy
:
Bind ViewModel property to DataGridComboBoxColum 将ViewModel属性绑定到DataGridComboBoxColum
Once you have setup the BindingProxy you can bind your DataGridTemplateColumn visiblity as 设置BindingProxy后,您可以将DataGridTemplateColumn可见性绑定为
<DataGridTemplateColumn Header="Apply" Visibility="{Binding Path=Data.Visible, Source={StaticResource ProxyElement}"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.