绑定的样式?

4

我有一个用户控件中的一些文本框:

<TextBox Text="{Binding Path=Name, UpdateSourceTrigger=PropertyChanged}"></TextBox>
<TextBox Text="{Binding Path=Street, UpdateSourceTrigger=PropertyChanged}"></TextBox>

在XAML中是否有一种类似于绑定样式的方法,使得我不必为每个文本框都写上 UpdateSourceTrigger=PropertyChanged ,而只需写 Path= 部分呢?

提前感谢您!

2个回答

5

每次我想要绑定属性时,写一些疯狂的长绑定语句真的让我很烦恼,因此在我偶然发现这篇文章之前,我已经这样做了一年多。

它基本上是将MarkupExtension(也就是一个Binding类)子类化为一个名为BindingDecoratorBase的抽象类,并提供了Binding类提供的所有属性。所以从那里你可以像这样做:

public class SimpleBinding : BindingDecoratorBase
{
  public SimpleBinding(string path) : this()
  {
    Path = new System.Windows.PropertyPath(path);
  }
  public SimpleBinding()
  {
    TargetNullValue = string.Empty;
    UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
  }
}

然后在你的XAML中,你只需要在顶部包含你的命名空间,然后要绑定控件就像这样:

<TextBox Text="{m:SimpleBinding Name}"></TextBox>
<TextBox Text="{m:SimpleBinding Street}"></TextBox>

这使得在绑定短语中写入较少内容时,比尝试子类化每个要编写的控件更容易。

这比子类化更好的方法。在这里,您可以将技术应用于任何控件上的任何绑定。您是否曾遇到过此技术的任何不足之处? - A.R.
并不是这样,恰恰相反。它给了我更多的控制权,例如,我曾经使用NotConverter将属性绑定到IsEnabled,但是通过这种方法,我允许一些C#语法,并让MarkupExtension为我否定。因此,我的MarkupExtension允许这种语法"{m:SimpleBinding !IsEnabled}" - Jose

2

不,没有通过XAML或样式的方法可以做到这一点。您最好的选择是构建一个自定义控件来更改默认行为。例如:

public class MyTextBox : TextBox {
    static MyTextBox() {
        TextProperty.OverrideMetadata(typeof(MyTextBox), new FrameworkPropertyMetadata() { DefaultUpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged });
    }
}

然后你需要使用 MyTextBox 代替 TextBox

谢谢您的努力。我已经尝试了那种解决方案,但是我还以为我在使用XAML方面遗漏了什么。不幸的是,并没有。 - Dummy01

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接