我有以下工作XAML代码,它基本上绑定了几个属性来计算我的用户控件的最终位置:
<UserControl x:Class="CurvePointControl"
....
>
<UserControl.Resources>
<local:VToYConverter x:Key="vToYConverter" />
</UserControl.Resources>
<UserControl.RenderTransform>
<TranslateTransform x:Name="XTranslateTransform" >
<TranslateTransform.Y>
<MultiBinding Converter="{StaticResource vToYConverter}">
<Binding ElementName="curveEditPoint" Path="V"/>
<Binding RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type local:CurveEditor}}" Path="MinV"/>
<Binding RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type local:CurveEditor}}" Path="MaxV"/>
<Binding RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type local:CurveEditor}}" Path="ActualHeight"/>
</MultiBinding>
</TranslateTransform.Y>
</TranslateTransform>
</UserControl.RenderTransform>
...
出于各种原因(但特别是为了避免相关来源,我现在正试图在代码中做同样的事情而没有成功。
这是我目前的代码:
public CurvePointControl(CurveEditor CV)
{
InitializeComponent();
MultiBinding multiBinding = new MultiBinding();
multiBinding.Converter = m_VToYConverter;
multiBinding.Bindings.Add(new Binding("V"));
multiBinding.Bindings.Add(new Binding(CV.MinVProperty)); // doesn't work
multiBinding.Bindings.Add(new Binding(CV.MaxVProperty)); // doesn't work
multiBinding.Bindings.Add(new Binding(CV.ActualHeight)); // doesn't work
multiBinding.NotifyOnSourceUpdated= true;
this.SetBinding(TranslateTransform.YProperty, multiBinding);
//Doesn't work too:
//BindingOperations.SetBinding(XTranslateTransform, TranslateTransform.YProperty, multiBinding);
}
我仍然无法相信将XAML转换为c#代码是如此困难。转换器被调用但只有一次且没有有效的属性值。
知道什么是错的吗? 我怎么能调试这个问题?
答案 0 :(得分:9)
您需要来源:
multiBinding.Bindings.Add(new Binding("V") { Source = curveEditPoint }); //If that object is accessible in the current scope.
multiBinding.Bindings.Add(new Binding("MinV") { Source = CV });
multiBinding.Bindings.Add(new Binding("MaxV") { Source = CV });
multiBinding.Bindings.Add(new Binding("ActualHeight") { Source = CV });
答案 1 :(得分:1)
字面翻译将是:
MultiBinding multiBinding = new MultiBinding();
multiBinding.Converter = m_VToYConverter;
RelativeSource relativeSource = new RelativeSource() { AncestorType = typeof(CurveEditor) };
multiBinding.Bindings.Add(new Binding("V") { ElementName = "curveEditPoint" });
multiBinding.Bindings.Add(new Binding(CV.MinVProperty) { RelativeSource = relativeSource });
multiBinding.Bindings.Add(new Binding(CV.MaxVProperty) { RelativeSource = relativeSource });
multiBinding.Bindings.Add(new Binding(CV.ActualHeight) { RelativeSource = relativeSource });
但是你可能会遇到ElementName正确解析的问题。在这种情况下,您必须直接绑定到元素或“找到”它。如果curveEditPoint是当前类中的一个字段,那么这样的东西就可以工作:
multiBinding.Bindings.Add(new Binding("V") { Source = this.curveEditPoint });
答案 2 :(得分:0)
尝试使用
multiBinding.Bindings.Add(new Binding("MinVProperty") { ElementName = CV.Name });
而不是
multiBinding.Bindings.Add(new Binding("CV.MinVProperty"));