假设我有2个属性CantTouchThis.First
和CantTouchThis.Second
,其中CantTouchThis
表示我无法挂钩INotifyPropertyChanged
实现。
我可以将它们绑定到两个滑块:
<Slider Value="{Binding CantTouchThis.First, Mode=TwoWay}" />
<Slider Value="{Binding CantTouchThis.Second, Mode=TwoWay}" />
<!-- textblocks just to display the values -->
<TextBlock Text="{Binding CantTouchThis.First, StringFormat={}{0:0.00}}" />
<TextBlock Text="{Binding CantTouchThis.Second, StringFormat={}{0:0.00}}" />
如何创建一个复选框(如果选中)将两个滑块和CantTouchThis.First
和CantTouchThis.Second
绑定在一起?
<CheckBox IsChecked="True" Content="Bind both together." Name="bindUsCheckbox" />
帮助永远赞赏,
标记
修改
我开始尝试使用IMultiValueConverter
来完成此操作,但在尝试以复选框为条件时遇到困难:
public class DuplicateValuesConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
return values[0];
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
object[] output = new object[2];
output[0] = value;
output[1] = value;
return output;
}
}
和这样的绑定:
<Slider.Value>
<MultiBinding Converter="{StaticResource magicConverter}" Mode="TwoWay">
<Binding Path="First" />
<Binding Path="Second" />
</MultiBinding>
</Slider.Value>
答案 0 :(得分:1)
在MultiBinding中包含checkbox.IsChecked值。使用converterParameter识别它是哪个滑块,并在不同步时返回它的值。
<Slider.Value>
<MultiBinding Converter="{StaticResource magicConverter}" Mode="TwoWay" ConverterParamter='0'>
<Binding Path="First" />
<Binding Path="Second" />
<Binding ElementName="bindUsCheckbox" Path="IsChecked" />
</MultiBinding>
</Slider.Value>
并像这样处理:
public class DuplicateValuesConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (bool.Parse(value[2].ToString()))
{ // keep sync
return values[0];
}
else
{
return values[int.Parse(parameter.ToString())];
}
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
object[] output = new object[2];
output[0] = value;
output[1] = value;
return output;
}
}