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.
I was having this exact same problem but mine wasn't because I was setting a local variable... I was in a child window, and I needed to set a relative DataContext which I just added to the Window XAML.
You can try x:Reference trick
One way would be to create an ObservableCollection (System.Collections.ObjectModel) and have your dictionary data in there. Then you should be able to bind the ObservableCollection to your ListBox.
In your XAML you should have something like this:
You can set the DataContext for your control, form, etc. like so:
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.