Wpf 如何在customcontrols上通过XAML绑定传递CommandParameter
我已经生成了一个CustomControl,其中包括一个文本框(以及其他元素)。绑定值可以: (Generic.xaml中的代码片段) 现在,随着转换器逻辑变得越来越复杂,我想在Wpf 如何在customcontrols上通过XAML绑定传递CommandParameter,wpf,xaml,data-binding,custom-controls,ivalueconverter,Wpf,Xaml,Data Binding,Custom Controls,Ivalueconverter,我已经生成了一个CustomControl,其中包括一个文本框(以及其他元素)。绑定值可以: (Generic.xaml中的代码片段) 现在,随着转换器逻辑变得越来越复杂,我想在参数转换器上使用参数属性。但不幸的是,由于参数不是dependencProperty,因此我无法将任何内容绑定到它。我在CustomControl中注册了一些DependencyProperty,但无法将其绑定到XAML中的ConverterParameter。我想要绑定到的ConverterParameter是一个名为
参数转换器
上使用参数
属性。但不幸的是,由于参数
不是dependencProperty
,因此我无法将任何内容绑定到它。我在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}'}"/>
难道没有更好、更干净、更简单的解决方案吗?我简直不敢相信没有办法绑定一个
ConverterParameter
如果需要多个值绑定,就使用一个。我知道如果我想传递多个值,我可以使用多个绑定。但是,这是将几个参数传递给ValueConverter的最常见的方法吗?然后我真的不明白IValueConverter
中的参数
是怎么引入的。@ElGaucho:这是针对不变的静态参数。也许我使用多值转换器时出错了,但是,当我没有获得转换方法所依赖的参数
的相关信息时,如何实现ConvertBack
方法?这类似于将“1000”(值)和“克”(参数)转换为“1”(千克)。在ConvertBack
方法中,我只获得关于“1”的信息,而没有获得关于参数的任何信息(“它是千克吗?是以英尺为单位测量的值吗?还是我应该转换压力、时间…?”)@ElGaucho:嗯,你需要转换回去吗?如果不是,您可以抛出一个NotSupportedException并处理它。您可以将参数设置为DependencyObject
的子类,然后该子类可以承载可绑定的依赖属性,但是树中有一个中断,因此您没有DataContext
,也不能使用ElementName
或RelativeSource
,请参阅以了解此类上下文中可能的解决方法。
<TextBox Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ParameterValue, Mode=TwoWay, Converter={StaticResource ParameterConverter}}"/>
<TextBox Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ParameterValue, Mode=TwoWay, Converter={StaticResource ParameterConverter}, ConverterParameter='{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ParameterUnit}'}"/>
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);
}