如何通过绑定通过自定义控件上的XAML传递CommandParameter
问题描述:
我已经生成了一个包含(除其他元素外)TextBox的CustomControl。绑定值的工作原理:如何通过绑定通过自定义控件上的XAML传递CommandParameter
(代码片段从Generic.xaml)
<TextBox Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ParameterValue, Mode=TwoWay }"/>
现在,我想一些ValueConverter添加到我的绑定,所以我实现了一个ParameterConverter
。使用转换器工作也(到目前为止),我可以看到正在转换的值。
<TextBox Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ParameterValue, Mode=TwoWay, Converter={StaticResource ParameterConverter}}"/>
现在我的转换器逻辑变得越来越复杂,我想用parameter
物业我ParameterConverter
。但不幸的是,因为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,如果我想通过多个值。但是,这是将几个参数传递给ValueConverter的最常见方式吗?然后我真的不明白为什么'IValueConverter'中的参数参数被引入。 – ElGaucho
@ElGaucho:它用于不改变的静态参数。 –
也许我在使用MultiValueConverter时出错了,但是如果我没有获取有关'convert'方法取决于的参数的信息,我该如何实现'ConvertBack'方法?这与将“1000”(Value)和“克”(参数)转换为“1”(千克)相似。在'ConvertBack'方法中,我只获得关于“1”的信息,但没有任何关于参数(“是千克?是以英尺测量的值还是应该转换压力,时间...?”) – ElGaucho