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.
There's a much easier way of doing this. You can assign a Name to your Window or UserControl, and then binding by ElementName.
Window1.xaml
Window1.xaml.cs
While Guy's answer is correct (and probably fits 9 out of 10 cases), it's worth noting that if you are attempting to do this from a control that already has its DataContext set further up the stack, you'll resetting this when you set DataContext back to itself:
This will of course then break your existing bindings.
If this is the case, you should set the RelativeSource on the control you are trying to bind, rather than its parent.
i.e. for binding to a UserControl's properties:
Given how difficult it can be currently to see what's going on with data binding, it's worth bearing this in mind even if you find that setting
RelativeSource={RelativeSource Self}
currently works :)Just a little more clarification: A property without 'get','set' won't be able to be bound
I'm facing the case just like the asker's case. And I must have the following things in order for the bind to work properly:
Make your property "windowname" a DependencyProperty and keep the remaining same.
Define a converter:
Bind to a custom definition of a Dictionary. There's lot of overrides that I've omitted, but the indexer is the important one, because it emits the property changed event when the value is changed. This is required for source to target binding.
In your .xaml file use this converter. First reference it:
Then, for instance, if your dictionary has an entry where the key is "Name", then to bind to it: use
In your code behind, set the window's DataContext to the dictionary. In your XAML, you can write:
This will bind the ListView to the dictionary.
For more complex scenarios, this would be a subset of techniques behind the MVVM pattern.