Binding objects defined in code-behind

wpf bind textbox to property in code behind
wpf binding code behind
wpf code-behind
wpf update textbox from code behind
uwp code behind binding
wpf code behind binding xaml
wpf datagridtextcolumn binding code behind
wpf set binding programmatically

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.

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.

Data binding via Code-behind, As we saw in the previous data binding examples, defining a binding by is very easy, but for certain cases, you may want to do it from Code-behind instead. to combine our newly created Binding object with the destination/target control,  In your code behind, set the window's DataContext to the dictionary. In your XAML, you can write: <ListView ItemsSource="{Binding}" /> This will bind the ListView to the dictionary. For more complex scenarios, this would be a subset of techniques behind the MVVM pattern.

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

<Window x:Class="QuizBee.Host.Window1"
        x:Name="Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <ListView ItemsSource="{Binding ElementName=Window1, Path=myDictionary}" />
</Window>

Window1.xaml.cs

public partial class Window1:Window
{
    // the property must be public, and it must have a getter & setter
    public Dictionary<string, myClass> myDictionary { get; set; }

    public Window1()
    {
        // define the dictionary items in the constructor
        // do the defining BEFORE the InitializeComponent();

        myDictionary = new Dictionary<string, myClass>()
        {
            {"item 1", new myClass(1)},
            {"item 2", new myClass(2)},
            {"item 3", new myClass(3)},
            {"item 4", new myClass(4)},
            {"item 5", new myClass(5)},
        }; 

        InitializeComponent();
    }
}

Binding to an Object/Field/Property Defined In CodeBehind , I'm pretty knew to data binding with Xamarin. It seems like a really powerful tool that comes at a cost of complexity. <local:MyUserControl x:Name="SomeUserControl"> <Button Command="{Binding ElementName=SomeUserControl, Path=DataContext.SaveCommand}" /> </local:MyUserControl > Or RelativeSource, which allows you to find an object relative to the current object to use as a DataSource

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:

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

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:

Binding Path=PropertyName, 
        RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}

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 :)

[Solved] How to bind code behind variables in WPF, Showing binding to a property in such a way as to allow for the Label to update on changes: PropertyChanged; /// <summary> /// Raises this object's PropertyChanged event. Define other settable properties similarly. If "1" is a property of the object returned by the index, then you just append it to the path "{Binding [MyIndex].1}" (assuming the binding source is a dictionary or a object which implements indexer).

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:

//(1) Declare a property with 'get','set' in code behind
public partial class my_class:Window {
  public String My_Property { get; set; }
  ...

//(2) Initialise the property in constructor of code behind
public partial class my_class:Window {
  ...
  public my_class() {
     My_Property = "my-string-value";
     InitializeComponent();
  }

//(3) Set data context in window xaml and specify a binding
<Window ...
DataContext="{Binding RelativeSource={RelativeSource Self}}">
  <TextBlock Text="{Binding My_Property}"/>
</Window>

Binding with Properties defined in Code Behind, For e.g., assigning a name to the code-behind object and then using ElementName in the data binding expression, using relative source with  Binding using DataContext of Window set to Self Here DataContext of entire window is set to code behind. All controls in this window would inherit this DataContext and hence their source for data binding would become code behind.

Define a converter:

public class RowIndexConverter : IValueConverter
{
    public object Convert( object value, Type targetType,
                           object parameter, CultureInfo culture )
    {
        var row = (IDictionary<string, object>) value;
        var key = (string) parameter;
        return row.Keys.Contains( key ) ? row[ key ] : null;
    }

    public object ConvertBack( object value, Type targetType,
                               object parameter, CultureInfo culture )
    {
        throw new NotImplementedException( );
    }
}

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.

public class BindableRow : INotifyPropertyChanged, IDictionary<string, object>
{
    private Dictionary<string, object> _data = new Dictionary<string, object>( );

    public object Dummy   // Provides a dummy property for the column to bind to
    {
        get
        {
            return this;
        }
        set
        {
            var o = value;
        }
    }


    public object this[ string index ]
    {
        get
        {
            return _data[ index ];
        }
        set
        {
            _data[ index ] = value;
            InvokePropertyChanged( new PropertyChangedEventArgs( "Dummy" ) ); // Trigger update
        }
    }


}

In your .xaml file use this converter. First reference it:

<UserControl.Resources>
    <ViewModelHelpers:RowIndexConverter x:Key="RowIndexConverter"/>
</UserControl.Resources>

Then, for instance, if your dictionary has an entry where the key is "Name", then to bind to it: use

<TextBlock  Text="{Binding Dummy, Converter={StaticResource RowIndexConverter}, ConverterParameter=Name}">

How to: Create a Binding in Code, If you are binding an element that inherits either of these classes, you can For the complete code sample, see Code-only Binding Sample. The code-behind file sets the binding with the SetBinding method defined by BindableObject. The argument is a constructor for the Binding class: public partial class AlternativeCodeBindingPage : ContentPage { public AlternativeCodeBindingPage() { InitializeComponent(); label.SetBinding(Label.ScaleProperty, new Binding("Value", source: slider)); } }

Data Binding XAML control to property in code behind, Binding to property defined in code behind using System. private void Window_Loaded(object sender, RoutedEventArgs e) { HelloText  For the complete code sample, see Code-only Binding Sample. Instead of calling SetBinding, you can use the SetBinding static method of the BindingOperations class. The following example, calls BindingOperations.SetBinding instead of FrameworkElement.SetBinding to bind myText to myDataProperty.

Everything you wanted to know about databinding in WPF , I showed how databindings can be created in code-behind, removing the In this blog post I'll look at how bindings can be defined in XAML,  Code-Behind and XAML in WPF. 03/30/2017; 3 minutes to read +9; In this article. Code-behind is a term used to describe the code that is joined with markup-defined objects, when a XAML page is markup-compiled.

Best Practices to Minimize or Eliminate using Code-Behind Files , Technically speaking, the two different files are "partial classes" written in two different Windows; namespace CodeBehind { public partial class MainWindow : Window { public Imagine, by comparison, what you'd have to do in C# to define a button like that. All XAML dialects provide a means of binding to commands. The above code snippet, an array, myEmp of three objects and an int type variable, count are defined in Window1 class. Default constructor of Window1 class initialze the count variable and three Employee objects of myEmp array. In the constructor Binding objects are defined and intializes with properties of Employee class.

Comments
  • Strangely enough, If I change the order of the property assignment of the window, It doesnt work. If I set "Title" Property followed by "DataContext" Property, binding doesnt happen. Can anyone explain this ? <Window x:Class="INotifyPropertyTest.MainWindow" xmlns="schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="schemas.microsoft.com/winfx/2006/xaml" xmlns:local ="clr-namespace:INotifyPropertyTest" Height="350" Width="525" DataContext="{Binding RelativeSource={RelativeSource self}}" Title="{Binding WindowName}" >
  • The "Self" here means the control, rather than the whole window class, is it?
  • Strange enough, Following is the code I have and it doesn't work as expected: public partial class Window1 : Window { public const string windowname = "ABCDEFG"; public Window1() { InitializeComponent(); } } <Window x:Class="QuizBee.Host.Window1" xmlns="schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="schemas.microsoft.com/winfx/2006/xaml" Title="{Binding windowname}" Height="300" Width="300" DataContext="{Binding RelativeSource={RelativeSource Self}}"> </Window>
  • Oh, it's ok now, I changed the windowname to be property instead of pure public variable and it can display now! thanks!
  • I can't imagine why this is not just set by default.
  • I had to change x:Name (compiler error CS0542). Then ElementName needs to be changed accordingly.
  • Silverlight 4 doesn't support FindAncestor. However it you need to do it this way you can implement FindAncestor as described on this site. http://blog.thekieners.com/2010/09/08/relativesource-binding-with-findancestor-mode-in-silverlight/
  • How exactly can you have a property without 'get' and 'set'? Wouldn't that be a field and not a property?