【发布时间】: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