2

Good Evening,

i have a simple Problem:

I know that I can bind objects in Context of Data like this:

//Class CustomObject with a Property named "Property" with value "obj1"
CustomObject obj1 = new CustomObject("obj1");
DataContext = obj1;
<TextBox Text="{Binding Property}" 

This works. But what is when I ve more than one object of a class. I tried something like this:

<TextBox Text="{Binding obj1.Property}" 

Unfortunatly it doesnt work. Know anyone how I can bind by object Name?

Thanks.

Edit: In C# its working with this Code:

CustomObject obj1 = new CustomObject("Test");
Binding myBinding = new Binding();
myBinding.Path = new PropertyPath("Property");
myBinding.Source = obj1;
textBox1.SetBinding(TextBox.TextProperty, myBinding);

So I tried the same in XAML, unfortunatly not sucessfully:

 <TextBox Text="{Binding Property, Source=Obj1}"/>

2 Answers 2

1

Try This:

<TextBox DataContext="{Binding Path=Obj1, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}}" Text="{Binding Property}"/>

In this example Obj1 would be a property of whatever window you are working programming. Obj2 would also be a property if you were planning on binding it to another textbox in the same window and so on ...

Sign up to request clarification or add additional context in comments.

Comments

0

You would create a view model class that holds the CustomObject instance as one it its properties.

public class MyViewModel
{
    public CustomObject Obj1 { get; set } 
    // declare other properties ...
}

Then assign an instance of the view model to the window's DataContext

var obj1 = new CustomObject("obj1");
var vm = new MyViewModel
{
    Obj1 = obj1
    // assign other properties ...
};
DataContext = vm;

Now bind to it like this:

<TextBox Text="{Binding Obj1.Property}" />

2 Comments

I don't want to use the mvvm pattern. I edited the Question - maybe you know the way how to do it? Thanks
As there can only be one object in the Window's DataContext, you'll have to assign an instance of a class with such properties. Alternatively, you could assign a CustomObject to the TextBox's DataContext in code behind.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.