所以我遇到了一个简单的 XAML 数据绑定错误。我有下面的 XAML,其中有两个类(到目前为止),它们用于 DataBinding,一个 Row,其中包含一个 ObservableCollection 行。这些节点有一堆额外的相关信息,我试图以类似网格的方式显示这些节点(它将用于寻路算法。)
问题是“这里”文本块没有出现。但我知道节点正在正确绑定,因为它们的值显示在 Debugging StackPanel 中。
<Window.Resources>
<local:Row x:Key="TestRow">
<local:Node x="0" y="0" Cost="20" />
<local:Node x="0" y="1" Cost="20" />
<local:Node x="0" y="2" Cost="20" />
</local:Row>
</Window.Resources>
<Grid Name="MainGrid" Margin="10,10,10,10" >
<Grid.RowDefinitions>
<RowDefinition Height="150" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<StackPanel Margin="0,25,0,0"
DataContext="{Binding ElementName=AStarListView,
Path=SelectedItem}"
x:Name="Debugging" Orientation="Vertical" >
<TextBlock Text="{Binding x}" />
<TextBlock Text="{Binding y}" />
<TextBlock Text="{Binding Cost}" />
</StackPanel>
<ListView Grid.RowSpan="2" Margin="2,2,2,2" Grid.Column="1"
x:Name="AStarListView"
ItemsSource="{StaticResource TestRow}" >
<ListView.ItemTemplate>
<DataTemplate DataType="local:Row">
<ListView ItemsSource="{Binding nodes}" Width="48" Height="48" >
<ListView.ItemTemplate>
<DataTemplate DataType="local:Node">
<TextBlock Text="Here" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
这是(剥离的)节点类。
public class Node : INotifyPropertyChanged
{
public Tuple<int, int> coordinates { get; set; }
public int x
{
get
{
if (this.coordinates == null)
return -1;
return this.coordinates.Item1;
}
set
{
if (this.coordinates != null)
this.coordinates = new Tuple<int, int>(value, y);
else
this.coordinates = new Tuple<int, int>(value, -1);
OnPropertyChanged("x");
}
}
public int y
{
get
{
if (this.coordinates == null)
return -1;
return this.coordinates.Item2;
}
set
{
if (this.coordinates != null)
this.coordinates = new Tuple<int, int>(x, value);
else
this.coordinates = new Tuple<int, int>(-1, value);
OnPropertyChanged("y");
}
}
private Node _parent;
private int _Cost;
public int Cost
{
get
{
return _Cost;
}
set
{
_Cost = value;
OnPropertyChanged("Cost");
}
}
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChangedEventArgs args =
new PropertyChangedEventArgs(propertyName);
this.PropertyChanged(this, args);
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
这是 Row 类:
public class Row : ObservableCollection<Node>
{
public ObservableCollection<Node> nodes { get; set; }
public Row()
{
this.nodes = new ObservableCollection<Node>();
}
}