0

In my Avalonia app, I need to create controls dynamically from a user control's code-behind so I can add them to a StackPanel inside that user control. I know the names of the viewmodel properties to which the dynamic controls' properties should be bound. A viewmodel object will be assigned as the dynamic controls' data context. What is the syntax I need to create the binding for a dynamic control for a given property by name?

For example, I create a checkbox whose IsChecked property is to be bound to my viewmodel's IsActivated property. In pure XAML, it would resemble:

<CheckBox IsChecked="{Binding IsActivated}" Content="Activated"/>

I'm looking for code-behind that looks something like:

var instanceVM = new TheViewModel { IsActviated = true };
var chkBox = new CheckBox { Content = "Activated" };
chkBox.Bind(TextBlock.TextProperty, "IsActivated");
myStackPanel.Children.Add(chkBox);
myStackPanel.DataContext = instanceVM;

How can I do this? Thanks...

3
  • 1
    docs.avaloniaui.net/docs/guides/data-binding/binding-from-code Commented Oct 27 at 5:13
  • You may perhaps use an ItemsControl with a collection of different item view models in its ItemsSource. Then declare appropriate DataTemplates for each view model type, as shown here: docs.avaloniaui.net/docs/concepts/templates/…. Commented Oct 27 at 7:41
  • @SirRufo I had come across that doc before, but I guess I didn't read it thoroughly enough! The stuff in the "Using XAML bindings from code" section seemed to do the trick, thanks so much for the lead. Commented Oct 27 at 20:35

1 Answer 1

0

Per the Avalonia document to which Sir Rufo linked in their comment, there's a way to assign the binding with the known property name at the time of the dynamic control's instantiation:

var chkBox = new CheckBox { Content = "Activated",
  [!CheckBox.IsCheckedProperty] = new Binding("IsActivated", BindingMode.TwoWay)
};

Specifying the Mode was actually not necessary for the CheckBox, but was for the "Value" dependency property of a custom control I created based on the NumericUpDown; without it, sets of the bound VM property would display in the UI, but user changes wouldn't change the VM property.

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

Comments

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.