简体   繁体   中英

WPF Binding directly to the DataContext

Is there a keyword to directly bind to the DataContext and not to an attribute of it?

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.

Here the 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":

<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. Make it just {Binding} . UpdateSourceTrigger=PropertyChanged is not needed because ItemsSource doesn't change from view.

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

alternatively use Path=. to code "bind entire DataContext here" requirement

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

any tricks with RelativeSource/ElementName are usually necessary to change binding source. In this case DataContext (binding source) is simply inherited from parent 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}" ... />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM