Binding objects defined in code-behind
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.
wpf xaml binding to object created in code behind
Set the Datacontext to myTestObject. Or, make a public property for myTestObject and set your Xaml binding to {Binding MyTestObjectPropertyHere.TestString}
For example:
public partial class MainWindow : Window
{
MyTestObject myTestObject;
public MainWindow()
{
myTestObject = new MyTestObject ();
this.DataContext = myTestObject;
InitializeComponent();
}
}
Xaml
<TextBox Text="{Binding Path=TestString}" />
Example with binding to the MainWindow as the datacontext:
public partial class MainWindow : Window
{
MyTestObject myTestObject;
public MyTestObject MyTestObjectProperty { get { return myTestObject; } }
public MainWindow()
{
myTestObject = new MyTestObject ();
this.DataContext = this;
InitializeComponent();
}
}
Xaml
<TextBox Text="{Binding Path=MyTestObjectProperty.TestString}" />
How to Bind to a property defined in code-behind from XAML
Use RelativeSource
.
If the code-behind is defined for your UserControl:
<TextBox Text="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=FoundationHeight}" />
Element Binding if both involved objects are created in code behind
It would be much simpler to set the Binding's Source
property instead of ElementName
:
binding.Source = border;
How to bind a property from code-behind while the rest are bound to DataContext?
Your code behind is in some UIElement, let say Window
. So give your element with code behind name and do bind to it. Of course property CodeBehindProperty
should be defined there.
<Window x:Name="_this">
<TextBox Text="{Binding CodeBehindProperty, ElementName=_this}"/>
</Window>
Another way is to find the ancestor with defined type:
<TextBox Text="{Binding CodeBehindProperty, RelativeSource={RelativeSource AncestorType=Window}}"/>
How to set {Binding} in code behind?
Do not set the Source
property of the Binding. You also did not do that in XAML.
The equivalent of the XAML expression Data="{Binding}"
is
BindingOperations.SetBinding(this, DataProperty, new Binding());
How to create databinding in code behind using the same object that is initiated in xaml?
Not sure why you don't set DataContext
of your MainWindow
to MainViewModel
.
<Window.DataContext>
<StaticResourceExtension ResourceKey="vmMain" />
</Window.DataContext>
Or, you can even set DataContext
via MainWindow
's code behind, which you don't seem to intent to not keep it untouched.
Then to set binding source:
myBinding.Source = this.DataContext;
In the case you refused to set the DataContext, you still can:
myBinding.Source = this.FindResource("vmMain") as MainViewModel;
Not sure if I managed to solve your problem.
Edit
I just realised your binding is in window2
. You should do this:
myBinding.Source = win.DataContext;
Similarly, myBinding.Source = this.FindResource("vmMain") as MainViewModel;
should also be changed to myBinding.Source = win.FindResource("vmMain") as MainViewModel;
.
This is provided you still have that MainWindow win = (MainWindow)Application.Current.MainWindow;
line there.
Related Topics
How to Store Data Locally in .Net (C#)
What Is a Good Unique Pc Identifier
Should I Use Appdomain.Currentdomain.Basedirectory or System.Environment.Currentdirectory
"Async Task Then Await Task" VS "Task Then Return Task"
Get Error Message If Modelstate.Isvalid Fails
Revisiting Task.Configureawait(Continueoncapturedcontext: False)
How to Use Shell32 Within a C# Application
A Type for Date Only in C# - Why Is There No Date Type
I am Getting Failed to Load Resource: Net::Err_Blocked_By_Client with Google Chrome
How to Write a Viewmodelbase in Mvvm
How to Generate a Constructor from Class Fields Using Visual Studio (And/Or Resharper)
Ascending/Descending in Linq - Can One Change the Order via Parameter
How to Extend Identityuser with Custom Property
Controlling Execution Order of Unit Tests in Visual Studio
How to Get Generic Type from a String Representation
Redirect Console.Writeline from Windows Application to a String