0

In order to create my GUI more dynamically I like to do a binding in XAML which I defined in Code:

Edit: I do not want call SetBinding() in code. I want to set the binding in XAML.

Code:

public class SPSProperty
{
    public string LabelContent { get; private set; }
    public string PropertyPath { get; private set; }

    public Binding Binding { get; private set; }

    public SPSProperty (INotifyPropertyChanged viewModel,string propertyPath, string labelContent)
    {
        LabelContent = labelContent;
        PropertyPath = propertyPath;
        Binding = new Binding(propertyPath);
        Binding.Source = viewModel;
    }
}

ViewModel:

public class MainWindowViewModel:BindableBase
{
    public SPSProperty Property { get; set; }

    public MainWindowViewModel()
    {
        Property = new SPSProperty(this, "Test_Property", "Test Property");
    }

    private string _Test_Property;
    public string Test_Property
    {
        get { return _Test_Property; }
        set { SetProperty(ref _Test_Property, value); }
    }
}

How can I use the binding in XAML?

TextBox Text="{Binding Property.Binding}" <=This does of course not work.

backer
  • 3
  • 4

1 Answers1

0

I created a Behaviour for my Textbox.

class DynamicBindingBehaviour: Behavior<TextBox>
{
    public static readonly DependencyProperty DynamicBindingProperty =
    DependencyProperty.Register("DynamicBinding", typeof(Binding), typeof(DynamicBindingBehaviour), new FrameworkPropertyMetadata());

    public Binding DynamicBinding
    {
        get { return (Binding)GetValue(DynamicBindingProperty); }
        set { SetValue(DynamicBindingProperty, value); }
    }


    protected override void OnAttached()
    {
        base.OnAttached();
        this.AssociatedObject.SetBinding(TextBox.TextProperty, DynamicBinding);
    }
}

And use it the in XAML by:

<TextBox DataContext="{Binding Path=Property}" >
      <i:Interaction.Behaviors>
           <local:DynamicBindingBehaviour DynamicBinding="{Binding Binding}"/>
      </i:Interaction.Behaviors>
</TextBox>
backer
  • 3
  • 4