Binding objects defined in code-behind

2020-01-25 05:16发布

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.

10条回答
兄弟一词,经得起流年.
2楼-- · 2020-01-25 05:35

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.

<Window x:Class="Log4Net_Viewer.LogItemWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    DataContext="{Binding RelativeSource={RelativeSource Self}}"
    Title="LogItemWindow" Height="397" Width="572">
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2020-01-25 05:37

You can try x:Reference trick

<Window ... x:Name="myWindow"><ListBox ItemsSource="{Binding Items, Source={x:Reference myWindow}}" /></Window>
查看更多
Fickle 薄情
4楼-- · 2020-01-25 05:44

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:

<ListBox ItemsSource="{Binding Path=Name_of_your_ObservableCollection" />
查看更多
来,给爷笑一个
5楼-- · 2020-01-25 05:46

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.

查看更多
登录 后发表回答