我希望能够在公制和帝国单位中显示距离。但是,通过ComboBox更改单位系统并没有更改标签的格式。
一些细节:
1)数据上下文正常工作
2)当我启动程序时,我会得到" 4.00 km",但更改Combobox的值没有效果。
3)ObservableObject具有OnPropertyChanged(),除此之外,它在任何地方都可以正常工作。
WPF UI
<ComboBox ItemsSource="{Binding UnitSystems}" SelectedValue="{Binding Units}"/>
<Label Content="{Binding Distance}" ContentStringFormat="{Binding DistanceFormat}"/>
c#查看模型
public class ViewModel : ObservableObject
{
private double distance = 4;
public double Distance
{
get
{
return distance;
}
set
{
distance = value;
OnPropertyChanged("Distance");
}
}
private UnitSystem units;
public List<UnitSystem> UnitSystems
{
get
{
return new List<UnitSystem>((UnitSystem[])Enum.GetValues(typeof(UnitSystem)));
}
}
public UnitSystem Units
{
get
{
return units;
}
set
{
units = value;
OnPropertyChanged("Units");
OnPropertyChanged("DistanceFormat");
OnPropertyChanged("Distance");
}
}
public string DistanceFormat
{
get
{
if (Units == UnitSystem.Metric)
return "0.00 km";
else
return "0.00 mi";
}
}
}
public enum UnitSystem
{
Metric,
Imperial
}
编辑:下面的多点线解决方案存在相同的问题,这不是因为格式字符串。使用F3和F4,我从" 4.000"开始,并且不会更改为" 4.0000"。
<ComboBox ItemsSource="{Binding UnitSystems}" SelectedValue="{Binding Units}"/>
<Label>
<Label.Content>
<MultiBinding Converter="{StaticResource FormatConverter}">
<Binding Path="Distance"/>
<Binding Path="DistanceFormat"/>
</MultiBinding>
</Label.Content>
</Label>
编辑2(已解决):问题在于,ObservableObject并未实现InotifyPropertychanged且出人意料地工作正常。
将 Units
绑定到 SelectedItem
而不是 SelectedValue
:
<ComboBox
ItemsSource="{Binding UnitSystems}"
SelectedItem="{Binding Units}"
/>
当您使用SelectedValuePath="SomePropertyName"
指定所关心的项目的属性时,使用 SelectedValue
。但是枚举没有属性,因此只需抓住项目本身即可。
这是我对ObservableObject
的替身:
public class ObservableObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string prop = null)
=> PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop));
}
没什么聪明的。我用片段创建那些。