我试图将祖先的ItemsControl.ItemTemplate源作为我的DataGrid源,但我无法处理这个案例。我在我的xaml中尝试了以下案例。但它没有用,datagrid是空的。
这是我的xaml:
.....
$user->password_hash = 'Debugging';
if ($user->save()){
var_dum('just for test');
$id = $user->id;
$assignment = 'AccessAdministrator';
$api->assignRole([$id,$assignment])
}
帐户属性实现如下:
<ItemsControl ItemsSource="{Binding Accounts}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Expander ExpandDirection="Down" FlowDirection=" RightToLeft">
<Expander.Header>
<DataGrid FlowDirection="LeftToRight"
ItemsSource="{RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemTemplate}}}">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding UserName}" />
<DataGridTextColumn Binding="{Binding Password}" />
</DataGrid.Columns>
</DataGrid>
</Expander.Header>
</Expander>
</DataTemplate>
</ItemsControl.ItemTemplate>
我的User.cs就像:
public List<User> Accounts = new List<User>();
Accounts.Add(new User("userName1","password1"));
Accounts.Add(new User("userName2","password2"));
答案 0 :(得分:3)
基本上,此代码不会创建绑定
ItemsSource="{RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemTemplate}}}"
祖先类型也不正确。
尝试这个绑定:
ItemsSource="{Binding Path=DataContext.Accounts, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}}"
或使用ElementName:
<ItemsControl Name="LstAccounts" ItemsSource="{Binding Accounts}">
和
ItemsSource="{Binding Path=DataContext.Accounts, ElementName=LstAccounts}"
上面的代码修复了绑定,但会产生意外结果。这是一个在DataGrid中显示单个对象的解决方案
对于ItemSource绑定我创建了一个转换器(my own older answer)
public class ItemsSourceConverter: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
// doesn't allow to add new rows in DataGrid
return Enumerable.Repeat(value, 1).ToArray();
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
这里是修改过的ItemsControl。转换器存储在资源中并用于ItemsSource绑定。 DataGrid自动生成列
<ItemsControl ItemsSource="{Binding Accounts}">
<ItemsControl.Resources>
<local:ItemsSourceConverter x:Key="Enumerator"/>
</ItemsControl.Resources>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Expander ExpandDirection="Down" FlowDirection=" RightToLeft">
<Expander.Header>
<DataGrid FlowDirection="LeftToRight"
ItemsSource="{Binding ., Converter={StaticResource Enumerator}}"/>
</Expander.Header>
</Expander>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
这是截图