我已使用以下代码Bind
ItemsSource
到ComboBox
列表的DistanceRoundoffs
。
我还将SelectedItem
的{{1}}绑定到ComboBox
属性。
RebarsVerticalDistanceRoundoff
我还实现了一个IValueConverter来将<ComboBox ItemsSource="{Binding Path=DistanceRoundoffs}"
SelectedItem="{Binding SettingsViewModel.RebarsVerticalDistanceRoundoff,
RelativeSource={RelativeSource FindAncestor, AncestorType=Window},
Mode=TwoWay}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Converter={StaticResource LengthConverter}}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
private List<double> distanceRoundoffs = new List<double> { 25, 50};
public List<double> DistanceRoundoffs
{
get { return distanceRoundoffs; }
set
{
distanceRoundoffs = value;
RaisePropertyChanged("DistanceRoundoffs");
}
}
private double rebarsVerticalDistanceRoundoff;
public double RebarsVerticalDistanceRoundoff
{
get { return rebarsVerticalDistanceRoundoff; }
set
{
rebarsVerticalDistanceRoundoff = value;
RaisePropertyChanged("RebarsVerticalDistanceRoundoff");
}
}
的值转换为另一个单位。转换器接受ComboBox
值并根据名为double
的参数更改其单位。
lfactor
当我们通过下面列出的另一个组合框更改单位时,会获得public class LengthConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var length = (double)value;
var lfactor = Building.LengthFactor;
return string.Format("{0}",length / lfactor);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value;
}
}
参数。
lfactor
DistanceRoundoffs的初始值在private void Units_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
GetLengthFactor();
// Building.LengthFactor is changed here! Later used in LengthConverter
}
:25,50
当我更改UnitComboBox时,mm
会触发,但Units_OnSelectionChanged
不会更新。
答案 0 :(得分:2)
使用MultiBinding的原始方法非常好。您只需确保单个绑定是正确的。在particalur中,“单位因子”绑定需要指定其源对象。
假设同一视图模型中存在LengthFactor
属性,其中包含DistanceRoundoffs
属性,DataTemplate将如下所示:
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock>
<TextBlock.Text>
<MultiBinding Converter="{StaticResource LengthConverter}">
<Binding Path="."/>
<Binding Path="DataContext.LengthFactor"
RelativeSource="{RelativeSource AncestorType=ComboBox}"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</DataTemplate>
</ComboBox.ItemTemplate>
LengthConverter现在实现IMultiValueConverter
,其Convert方法如下所示:
public object Convert(
object[] values, Type targetType, object parameter, CultureInfo culture)
{
return ((double)values[0] *(double)values[1]).ToString();
}
答案 1 :(得分:1)
WPF不知道所选单位与距离舍入显示之间的关系。只要没有DistanceRoundoffs
已发生变化的信号,它就没有理由更新该组合框。
因此,当所选单位发生变化时,您必须通过为PropertyChanged
举起DistanceRoundoffs
事件来给出信号,例如:在所选单位财产的设定者中。