【问题标题】:How to pass CommandParameter by Binding through XAML on customcontrols如何通过自定义控件上的 XAML 绑定来传递 CommandParameter
【发布时间】:2011-12-02 07:54:15
【问题描述】:

我生成了一个包含(以及其他元素)一个 TextBox 的 CustomControl。绑定值有效:

(来自 Generic.xaml 的代码片段)

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

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

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

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

<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

【问题讨论】:

    标签: wpf xaml data-binding custom-controls ivalueconverter


    【解决方案1】:

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

    【讨论】:

    • 我知道如果我想传递多个值,我可以使用 MultiBinding。但这是将多个参数传递给 ValueConverter 的最常见方法吗?然后我真的不明白IValueConverter 中的parameter 参数是什么引入的。
    • @ElGaucho:用于不改变的静态参数。
    • 也许我在使用 MultiValueConverter 时遇到了问题,但是当我没有关于我的转换方法所依赖的 parameter 的信息时,如何实现 ConvertBack 方法?类似于将“1000”(值)和“克”(参数)转换为“1”(千克)。在ConvertBackmethod 上,我只获得关于“1”的信息,但没有关于参数的信息(“是公斤吗?是以英尺为单位测量的值吗?或者我应该转换压力,时间......?”)跨度>
    • @ElGaucho:嗯,你需要转换回来吗?如果没有,你可以抛出一个 NotSupportedException 并完成它。
    • 您可以将参数设置为DependencyObject 的子类,然后可以托管可以绑定的依赖项属性,但是树中有一个中断,因此您没有DataContext 并且您也不能使用ElementNameRelativeSource,请参阅this answer 了解在这种情况下可能的解决方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-29
    • 1970-01-01
    • 2020-08-30
    • 2010-12-26
    • 1970-01-01
    相关资源
    最近更新 更多