WPF绑定到代码中定义的绑定

时间:2018-02-07 10:26:56

标签: c# wpf xaml

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

修改 我不想在代码中调用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;
    }
}

视图模型:

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}”< =这当然不起作用。

1 个答案:

答案 0 :(得分:0)

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

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>