WPF MultiBindings
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" />开发者_C百科;
<Binding ElementName="SecondSlider" Path="Value" />
<Binding ElementName="ThirdSlider" Path="Value" />
</MultiBinding>
in C# ?
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")
});
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)
- 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;
}
精彩评论