如何在自定义控件上通过XAML绑定传递CommandParameter



我已经生成了一个CustomControl,其中包括(在其他元素中)一个TextBox。绑定值有效:

(来自Generic.xaml代码片段)

<TextBox Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ParameterValue, Mode=TwoWay }"/>

现在,我想添加一些ValueConverter到我的绑定,所以我实现了一个ParameterConverter。使用Converter (到目前为止),我可以看到被转换的值。

<TextBox Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ParameterValue, Mode=TwoWay, Converter={StaticResource ParameterConverter}}"/>

现在,由于我的转换器逻辑变得更加复杂,我想在我的ParameterConverter上使用parameter属性。但不幸的是,由于parameter不是DependencyProperty,我不能将任何东西绑定到它。我已经在我的CustomControl中注册了一些DependencyProperty,但我无法将其绑定到我的XAML中的ConverterParameter。我想要绑定到的ConverterParameter是一个名为ParameterUnit的Enum。我所期望的结果应该看起来像这样:

<TextBox Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ParameterValue, Mode=TwoWay, Converter={StaticResource ParameterConverter}, ConverterParameter='{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ParameterUnit}'}"/>

我有一个解决方案,但看起来真的很讨厌,违反了我想要尽可能遵循的ccd原则。我在ParameterControl -Class中添加了一些代码:

public ParameterControl()
    {
        _textBox = (TextBox)Template.FindName("ParameterValueTextBox", this);
        this.Loaded += (s, e) => SetupControl();
    }
public void SetupControl()
    {
        var textBinding = new Binding();
        textBinding.RelativeSource = RelativeSource.TemplatedParent;
        textBinding.Path = new PropertyPath("ParameterValue");
        textBinding.Converter = new ParameterToHumanFormatConverter();
        textBinding.ConverterParameter = ParameterUnit;
        textBinding.Mode = BindingMode.TwoWay;
        textBinding.UpdateSourceTrigger = UpdateSourceTrigger.LostFocus;  
        _textBox.SetBinding(TextBox.TextProperty, textBinding);
    }
难道没有更好、更干净、更容易的解决办法吗?我简直不敢相信居然没有办法绑定ConverterParameter

如果需要多个值绑定,只需使用MultiBinding

最新更新