【问题标题】:WPF Binding to Binding defined in codeWPF 绑定到代码中定义的绑定
【发布时间】:2018-07-17 14:26:03
【问题描述】:

为了更动态地创建我的 GUI,我喜欢在 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;
    }
}

视图模型:

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}"

【问题讨论】:

  • 这行得通吗? TextBox DataContext="{Binding Path=Property}" Text="{Binding Path=Binding}"
  • @ViRuSTriNiTy 它确实可以正常工作,我喜欢在最后设置 Test_Property。

标签: c# wpf xaml


【解决方案1】:

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

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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-20
    • 2023-03-20
    • 2018-11-24
    • 2011-09-20
    • 2018-12-16
    • 2011-07-27
    相关资源
    最近更新 更多