WPF直接绑定到DataContext

时间:2018-07-21 12:26:56

标签: c# wpf

是否有一个关键词可以直接绑定到DataContext而不是它的属性? 这样可以节省我很多时间。我听说了有关Self Object的解决方法。我的想法是,我打开一个窗口,并给ObservableCollection作为参数,并将其设置为DataContext。

这里是WPF(xaml.cs)ctor

  public Depot(ObservableCollection<ObservableCollection<ItemManager.Item>> totalDepot)
    {
        this.FullDepotList = totalDepot;
        this.DataContext = FullDepotList[1];
        InitializeComponent();
    }

我最好将XAML代码片段直接绑定到DataContext或“ this”:

 <WrapPanel>
        <ListBox 
             ItemsSource="{Binding this, UpdateSourceTrigger=PropertyChanged}"       
             ItemTemplate="{DynamicResource ItemWithCoolTooltipTemplate}" 
             Focusable="False">
        </ListBox>
 </WrapPanel>

感谢您的帮助:D

2 个答案:

答案 0 :(得分:3)

要直接绑定到DataContext而不是它的属性,请不要编写任何绑定Path。将其设置为{Binding}。不需要UpdateSourceTrigger=PropertyChanged,因为ItemsSource不会从视图中更改。

<ListBox 
     ItemsSource="{Binding}"
     ItemTemplate="{DynamicResource ItemWithCoolTooltipTemplate}" 
     Focusable="False">
</ListBox>

或者使用Path=.编码“在此处绑定整个DataContext”要求

<ListBox 
     ItemsSource="{Binding Path=.}"
     ItemTemplate="{DynamicResource ItemWithCoolTooltipTemplate}" 
     Focusable="False">
</ListBox>

通常需要使用带有RelativeSource / ElementName的技巧来更改绑定源。在这种情况下,DataContext(绑定源)只是从父Window继承而来。

答案 1 :(得分:1)

您可以尝试以下技巧。 将名称属性添加到您的窗口-<Window ... Name="myWindow" ...> 使用这样的构造绑定到属性或您需要的任何内容-<ListBox ItemsSource="{Binding Path=DataContext, ElementName=myWindow}" ... />

相关问题