xandy xandy - 2 months ago 17
C# Question

Binding objects defined in code-behind

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<string, myClass> myDictionary;


How can I bind this object to, for example, a list view, using only XAML markups?

Update:

(This is exactly I have in my test code):

<Window x:Class="QuizBee.Host.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="{Binding windowname}" Height="300" Width="300"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Grid>
</Grid>
</Window>


And in codebehind

public partial class Window1 : Window
{
public const string windowname = "ABCDEFG";

public Window1()
{
InitializeComponent();
}
}


Suppose the title should become "ABCDEFG" right? but it ends up showing nothing.

Answer

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:

<Window x:Class="MyClass"
  Title="{Binding windowname}"
  DataContext="{Binding RelativeSource={RelativeSource Self}}"
  Height="470" Width="626">

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.

Comments