WPF与代码中定义的绑定结合



,为了更动态地创建我的GUI,我喜欢在XAML中进行绑定,我在代码中定义了XAML:

编辑:我不想在代码中调用setBinding((。我想在xaml中设置绑定。

代码:

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); }
    }
}

如何在XAML中使用绑定?

textbox text =" {binding property.binding}"< =这当然不起作用。

我为文本框创建了一个行为。

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);
    }
}

并在xaml中使用它:

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

最新更新