我已經生成了一個包含(除其他元素外)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