【发布时间】:2017-07-16 02:01:23
【问题描述】:
编辑:已解决
(我在ViewModel wrapper 中创建了另一个属性并绑定到该属性)
我正在尝试绑定与DataGrid 绑定的ObservableCollection 无关的属性。其他列正在以应有的方式绑定,只是这一列我似乎无法开始工作。
我尝试使用RelativeSource AncestorType 绑定属性并直接绑定到DataContext,但没有成功。
XAML,我绑定的ObservableCollection 显然被称为MonthlyRecords,它是一个不同类的集合,它以它应该的方式绑定。让我伤心的是propertySelectedTenant.FullName与收藏无关。
<DataGrid ItemsSource="{Binding MonthlyRecords}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTemplateColumn Header="Name">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<!--Trying to bind this Property in the next line-->
<TextBlock Text="{Binding Path=SelectedTenant.FullName}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Width="60" Header="Code" Binding="{Binding UpdateSourceTrigger=LostFocus, Path=TenantCode}" />
这是我要绑定的属性的类。
public class Tenant
{
public Tenant()
{
}
public int Code { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public string FullName => LastName + " " + FirstName;
public string Section { get; set; }
public Tenant(int code, string lastName = null, string firstName = null, string section = null)
{
Code = code;
LastName = lastName;
FirstName = firstName;
Section = section;
}
}
这是我试图绑定到的 ViewModel 中的property。
private Tenant _selectedTenant;
public Tenant SelectedTenant
{
get { return _selectedTenant; }
set
{
if (Equals(_selectedTenant, value)) return;
_selectedTenant = value;
OnPropertyChanged();
}
}
我还需要做什么才能将其绑定到DataGrid?
【问题讨论】:
-
MonthlyRecords 是 Tenant 的集合吗?那为什么不能直接在网格列中绑定 FullName 属性而不是 Name?
-
@SushilMate,
MonthlyRecords是与Tenant完全不同的类的集合。这就是我遇到麻烦的原因。 -
如何在 xaml 中绑定 SelectedTenant?如果您也显示该代码
-
@SushilMate,您确定您没有阅读其他问题吗?这一切都在那里。我有我用来尝试绑定问题中的属性的 XAML。我什至在里面放了一条评论来显示我在哪里绑定它
-
我的意思是说,除了数据网格之外,您是否在 xaml 中绑定 SelectedTenant,我已经通过相关源查看它。