我在XAML中静态创建了ListView
ListViewItem
。我想将ListViewItem
的属性绑定到我的视图模型中的不同属性,作为DataContext
的{{1}}给出。但我的代码不起作用:
ListView
NumericItem的位置:
<ListView AlternationCount="2" Name="listView">
<ListView.View>
<GridView>
<GridViewColumn>
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Title}" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn>
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBox Binding.TargetUpdated="TargetUpdated" Text="{Binding Value}" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn>
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Units}" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn>
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding About}" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
<l:PropertyItem Title="title" Value="{Binding Path=DeviceCode}" Units="units" About="about"/>
<l:PropertyItem Title="title" Value="{Binding Path=VendorName}" Units="units" About="about"/>
<l:PropertyItem Title="title" Value="{Binding Path=Version}" Units="units" About="about"/>
</ListView>
答案 0 :(得分:1)
我找到了解决方案!我的PropertyItem
类派生自DependencyObject
,后者不包含属性DataContext
。这就是绑定不起作用的原因。您需要从拥有DataContext
属性的人那里派生,例如FrameworkElement
,它会起作用!
答案 1 :(得分:0)
尝试使用这些Binding
s:
<l:PropertyItem Title="title" Value="{Binding Path=DataContext.DeviceCode,
RelativeSource={RelativeSource AncestorType={x:Type ListView}}}" Units="units"
About="about" />
<l:PropertyItem Title="title" Value="{Binding Path=DataContext.VendorName,
RelativeSource={RelativeSource AncestorType={x:Type ListView}}}" Units="units"
About="about"/>
<l:PropertyItem Title="title" Value="{Binding Path=DataContext.Version,
RelativeSource={RelativeSource AncestorType={x:Type ListView}}}" Units="units"
About="about"/>
在这里,我们绑定到DataContext
类型父级的ListView
...我相信这就是你所追求的。