Cgt*_*Cgt 0 c# data-binding wpf xaml mvvm
假设我有这个 ViewModel 和 xaml:
class MyViewModel
{
public MyStringValue {get;set;} = "HelloWorld"
public IList<CustomObject> ChildViewModels{get;set;}
}
<DataTemplate DataType="{x:Type local:MyViewModel}">
<ItemsControl ItemsSource="{Binding ChildViewModels}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<TextBlock Text="{Binding Path=MyStringValue,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType={x:Type local:MyViewModel}}}"/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</DataTemplate>
Run Code Online (Sandbox Code Playgroud)
我不断收到此错误消息:“无法找到使用引用 'RelativeSource FindAncestor ... 进行绑定的源...” 所以基本上,我正在尝试绑定 ItemsControl 的父属性容器,但似乎我不能。
RelativeSource AncestorType是属于更高级别的视觉树(ItemsControl这里)的东西。
由于MyStringValue不是 的属性ItemsControl,您也应该更改Binding Path为指向视图模型 ( DataContext):
{Binding Path=DataContext.MyStringValue,
RelativeSource={RelativeSource AncestorType=ItemsControl}}"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2534 次 |
| 最近记录: |