4

我需要不使用 XAML 直接在 C# 中实现 MultiBindings,我知道如何在 C# 中使用 IMultiValueConverter,但是,该怎么做:

<MultiBinding Converter="{StaticResource sumConverter}">
  <Binding ElementName="FirstSlider" Path="Value" />
  <Binding ElementName="SecondSlider" Path="Value" />
  <Binding ElementName="ThirdSlider" Path="Value" />
</MultiBinding>

在 C# 中?

4

2 回答 2

4

为什么不使用 XAML?

以下代码应该可以工作:

MultiBinding multiBinding = new MultiBinding();

multiBinding.Converter = converter;

multiBinding.Bindings.Add(new Binding
{
    ElementName = "FirstSlider",
    Path = new PropertyPath("Value")
});
multiBinding.Bindings.Add(new Binding
{
    ElementName = "SecondSlider",
    Path = new PropertyPath("Value")
});
multiBinding.Bindings.Add(new Binding
{
    ElementName = "ThirdSlider",
    Path = new PropertyPath("Value")
});
于 2010-03-01T08:51:54.230 回答
0

有两种方法可以在 C# 端执行此操作(我假设您只是不想将 MultiBinding 从字面上移植到后面的代码中,如果这样做真的是毫无价值的努力,XAML 总是更好)

  1. 简单的方法是为 3 个滑块创建 ValueChanged 事件处理程序并在那里计算总和并分配给所需的属性。

2 . Second and the best way to approach these in WPF is to make the application MVVM style.(I am hoping you are aware of MVVM). In your ViewModel class you will have 3 different properties. And you need another 'Sum' property also in the class. The Sum will get re-evaluated whenever the other 3 property setter gets called.

public double Value1
 {
     get { return _value1;}
     set { _value1 = value;  RaisePropertyChanged("Value1"); ClaculateSum(); }
 }
 public double Sum
 {
     get { return _sum;}
     set { _sum= value;  RaisePropertyChanged("Sum"); }
 }
 public void CalculateSum()
 {
   Sum = Value1+Value2+Value3;
 }
于 2010-03-01T08:52:14.423 回答