[英]WPF Binding directly to the DataContext
Is there a keyword to directly bind to the DataContext and not to an attribute of it?是否有直接绑定到 DataContext 而不是它的属性的关键字?
I heard about the workaround with a Self Object.我听说过使用自对象的解决方法。 My problem is that I open a Window, and give an ObservableCollection as argument, which is set to the DataContext.我的问题是我打开一个窗口,并给出一个 ObservableCollection 作为参数,它被设置为 DataContext。
Here the WPF(xaml.cs) ctor这里是 WPF(xaml.cs) ctor
public Depot(ObservableCollection<ObservableCollection<ItemManager.Item>> totalDepot)
{
this.FullDepotList = totalDepot;
this.DataContext = FullDepotList[1];
InitializeComponent();
}
The XAML Code snippet where I would preferably bind to the DataContext directly or to "this":我最好直接绑定到 DataContext 或绑定到“this”的 XAML 代码片段:
<WrapPanel>
<ListBox
ItemsSource="{Binding this, UpdateSourceTrigger=PropertyChanged}"
ItemTemplate="{DynamicResource ItemWithCoolTooltipTemplate}"
Focusable="False">
</ListBox>
</WrapPanel>
To bind directly to the DataContext and not to an attribute of it, don't write any binding Path.要直接绑定到 DataContext 而不是绑定到它的属性,请不要编写任何绑定路径。 Make it just {Binding}
.让它只是{Binding}
。 UpdateSourceTrigger=PropertyChanged
is not needed because ItemsSource doesn't change from view. UpdateSourceTrigger=PropertyChanged
不是必需的,因为 ItemsSource 不会从视图中改变。
<ListBox
ItemsSource="{Binding}"
ItemTemplate="{DynamicResource ItemWithCoolTooltipTemplate}"
Focusable="False">
</ListBox>
alternatively use Path=.
或者使用Path=.
to code "bind entire DataContext here" requirement编码“在此处绑定整个 DataContext”要求
<ListBox
ItemsSource="{Binding Path=.}"
ItemTemplate="{DynamicResource ItemWithCoolTooltipTemplate}"
Focusable="False">
</ListBox>
any tricks with RelativeSource/ElementName are usually necessary to change binding source.使用 RelativeSource/ElementName 的任何技巧通常都是更改绑定源所必需的。 In this case DataContext (binding source) is simply inherited from parent Window.在这种情况下,DataContext(绑定源)只是从父 Window 继承而来。
You can try the following trick.您可以尝试以下技巧。 Add name property to your Window - <Window ... Name="myWindow" ...>
Use such a construction to bind to the property or whatever you need - <ListBox ItemsSource="{Binding Path=DataContext, ElementName=myWindow}" ... />
将 name 属性添加到您的 Window - <Window ... Name="myWindow" ...>
使用这样的构造来绑定到该属性或您需要的任何内容 - <ListBox ItemsSource="{Binding Path=DataContext, ElementName=myWindow}" ... />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.