Binding objects defined in code-behind

前端 未结 11 1283
难免孤独
难免孤独 2020-11-28 04:29

I have some object that is instantiated in code behind, for instance, the XAML is called window.xaml and within the window.xaml.cs

protected Dictionary

        
11条回答
  •  渐次进展
    2020-11-28 04:39

    You can set the DataContext for your control, form, etc. like so:

    DataContext="{Binding RelativeSource={RelativeSource Self}}"
    

    Clarification:

    The data context being set to the value above should be done at whatever element "owns" the code behind -- so for a Window, you should set it in the Window declaration.

    I have your example working with this code:

    
    

    The DataContext set at this level then is inherited by any element in the window (unless you explicitly change it for a child element), so after setting the DataContext for the Window you should be able to just do straight binding to CodeBehind properties from any control on the window.

提交回复
热议问题