您好以下建议
您有一个 DataContext 是的文本块:
- 这个[0]
- 这个[1]
- 这个[...]
- 这个[n]
此文本块是 DatagridCell 的子项
现在我想根据列位置设置一个绑定
所以我写了Binding RelativeSource={RelativeSource FindAncestor,AncestorType=DataGridCell},Path=Column.DisplayIndex }
哪些工作正常
要得到一个 this[...] 我需要像Binding Path=[0]
这样也可以很好地绑定
但是如果我像这样在一起:
{ Binding Path=[ {Binding Path=Column.DisplayIndex, RelativeSource={RelativeSource FindAncestor, AncestorType=DataGridCell}} ] }
它不在这里绑定错误
System.Windows.Data Error: 40 : BindingExpression path error: '[]' property not found on 'object' ''List`1' (HashCode=33153114)'. BindingExpression:Path=[{Binding Path=Column.DisplayIndex, RelativeSource={RelativeSource FindAncestor, AncestorType=DataGridCell} }]; DataItem='List`1' (HashCode=33153114); target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String')
那么有人知道该怎么做吗?
编辑:
这里简单的代码:
XAML
<DataGrid AutoGenerateColumns="true" Height="200" HorizontalAlignment="Left" Margin="243,12,0,0" Name="grid" VerticalAlignment="Top" Width="200"
SelectionMode="Extended" SelectionUnit="Cell">
<DataGrid.Resources>
<Style TargetType="{x:Type DataGridCell}">
<Setter Property="Background" Value="Green"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="DataGridCell">
<StackPanel >
<TextBlock Text="{Binding Path=Column.DisplayIndex, RelativeSource={RelativeSource FindAncestor, AncestorType=DataGridCell} }" />
<TextBlock Text="{Binding Path=[0] }" />
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</DataGrid.Resources>
</DataGrid>
CS
/// <summary>
/// Interaktionslogik für MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var gridList = new List<List<MyCell>>();
for (int i = 0; i < 5; i++)
{
var cell1 = new MyCell { Text1 = "nr " + i, Text2 = "value1" };
var cell2 = new MyCell { Text1 = "nr " + i, Text2 = "value2" };
var sublist = new List<MyCell>();
sublist.Add(cell1);
sublist.Add(cell2);
gridList.Add(sublist);
}
grid.ItemsSource = gridList;
}
}
public class MyCell
{
string value1;
string value2;
public string Text1
{
get { return value1; }
set { value1 = value; }
}
public string Text2
{
get { return value2; }
set { value2 = value; }
}
}