WPF MultiBindings

…衆ロ難τιáo~ 提交于 2019-12-07 07:30:50

问题


I need to implement MultiBindings in C# directly without using XAML, I know how to use the IMultiValueConverter in C#, but, how to do:

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

in C# ?


回答1:


Why not using XAML?

The following code should work:

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")
});



回答2:


There are two ways you can do this to C# side (I am assuming you just dont want to literally port the MultiBinding to code behind, which is really a worthless effort if you do so, XAML is always better for that)

  1. Simple way is to make ValueChanged event handler for 3 sliders and calculate the sum there and assign to the required property.

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;
 }


来源:https://stackoverflow.com/questions/2354613/wpf-multibindings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!