How to Set a Binding in Code

How to set a binding in Code?

Replace:

myBinding.Source = ViewModel.SomeString;

with:

myBinding.Source = ViewModel;

Example:

Binding myBinding = new Binding();
myBinding.Source = ViewModel;
myBinding.Path = new PropertyPath("SomeString");
myBinding.Mode = BindingMode.TwoWay;
myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
BindingOperations.SetBinding(txtText, TextBox.TextProperty, myBinding);

Your source should be just ViewModel, the .SomeString part is evaluated from the Path (the Path can be set by the constructor or by the Path property).

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 can I create a binding in code-behind that doesn't specify a Path?

The binding engine subscribes to INPC and DP-changes on the Source object (and non-leaves on the Path), and checks whether the Path property/properties was/were changed. If there is no Path there are no notifications. A rather unfortunate drawback.

(I might be oversimplifying the system a bit but the essence is that there are no updates to source-changes, they are not and cannot be monitored)


{Binding} is equivalent to new Binding() (no additional properties), this binding may update as there are events for DataContext changes.

Binding in code behind in WPF

GreenscreenEffect effect = new GreenscreenEffect() ;
Binding binding = new Binding();
binding.Path = new PropertyPath("Value");
binding.Source = sliderGreenscreenTolerance;
// effect.SetBinding(GreenscreenEffect.ToleranceProperty, binding);
// Commented above out since GreenscreenEffect is not a FrameworkElement, thus:
BindingOperations.SetBinding(effect, GreenscreenEffect.ToleranceProperty, binding);
// ... ColorRProperty etc...

How Do I Bind Properties in Code Behind WPF

Make sure you create the Line and Ellipse elements only once, and assign the Bindings only once. Assign the MouseMove handler to the Canvas instead of the Ellipse:

private Line line;
private Ellipse ellipse;

public MainWindow()
{
InitializeComponent();

line = new Line
{
Stroke = Brushes.Blue,
StrokeThickness = 2
};

ellipse = new Ellipse
{
Stroke = Brushes.Blue,
StrokeThickness = 1,
Width = 20,
Height = 20,
Margin = new Thickness(-10)
};

Binding xBinding = new Binding
{
Source = ellipse,
Path = new PropertyPath(Canvas.LeftProperty)
};
line.SetBinding(Line.X1Property, xBinding);

Binding yBinding = new Binding
{
Source = ellipse,
Path = new PropertyPath(Canvas.TopProperty)
};
line.SetBinding(Line.Y1Property, yBinding);

testcanv.Children.Add(line);
testcanv.Children.Add(ellipse);

testcanv.Background = Brushes.Transparent;
testcanv.MouseMove += adjustRoute;
}

private void adjustRoute(object sender, MouseEventArgs e)
{
var p = e.GetPosition(testcanv);
Canvas.SetLeft(ellipse, p.X);
Canvas.SetTop(ellipse, p.Y);
}

Binding properties in code behind

Here's how you define and apply a binding in code:

Binding binding = new Binding {
Source = TitleLabel,
Path = new PropertyPath("Content"),
};
BottomLabel.SetBinding(ContentControl.ContentProperty, binding);

Note that on objects that don't derive from FrameworkElement, you have to explicitly use BindingOperations.SetBinding() instead of element.SetBinding():

BindingOperations.SetBinding(BottomLabel, ContentControl.ContentProperty, 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.

How to use binding in a label in code behind

If you read the Basic Binding documentation, then it clearly states that to bind a view you have to.

  1. Specify a BindingContext
  2. Use the SetBinding method to specify the target property to be bound to which ViewModel source property.

The BindingContext may be inferred from the parent element and does not always have to be specified, but your binding should look more like:

var label = new Label();
label.SetBinding(Label.TextProperty, "LastName");

This will bind the Text property on the label to LastName in the ViewModel.

How to set a Bindíng in C#

At a very very basic level, binding is done by using the DataContext property of a UI element. For example, if you had a Person class:

public class Person
{
public string FirstName {get;set;}
public string LastName {get;set;}
}

You can then use binding to bind these properties to UI elements without explicitly setting them. An example of this would be if you had a StackPanel

<StackPanel x:Name="MyStack" Orientation="Horizontal">
<TextBlock Text="{Binding FirstName}"/>
<TextBlock Text="{Binding LastName}"/>
</StackPanel>

This XAML will look for any properties named FirstName or LastName in the DataContext that is set. So by setting the DataContext to a Person object, it can display the data we specify.

MyStack.DataContext = new Person(){ FirstName = "Test", LastName = "Man"};

This will then tell the StackPanel to populate those two textboxes with 'Test' and 'Man'.

This logic extends to any types of UI objects, such as SolidColorBrush for setting colours. If you extended the Person class to accept a SolidColorBrush for a FavColor property, you could then set the background of the panel by setting a binding for that too, i.e.

<StackPanel x:Name="MyStack" Background="{Binding FavColor}" Orientation="Horizontal">

However, as mentioned, you really want to keep your models (the objects that contain the data you want to display, like our Person, or a User, or a Shape, etc) and any sort of View information completely separate. To read more into how to do this, I would look into the Model View View-Model (MVVM) pattern, which focuses heavily on XAML data binding. There are plenty of good tutorials out there, I used video examples to help me get an understanding, so it may be worth searching for these too to expand your knowledge.



Related Topics



Leave a reply



Submit