WPF格式绑定不起作用

时间:2017-03-08 01:14:25

标签: c# wpf mvvm data-binding

我希望能够以公制和英制单位显示距离。但是,通过ComboBox更改单位系统并不能改变标签的格式。

一些细节:

1)数据上下文工作正常

2)我得到了4.00公里"当我启动程序但更改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,我从&#34; 4.000&#34;开始并且它不会改变为&#34; 4.0000&#34;。

    <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,并且令人惊讶地工作到目前为止。

1 个答案:

答案 0 :(得分:1)

Units绑定到SelectedItem而不是SelectedValue

<ComboBox 
    ItemsSource="{Binding UnitSystems}"
    SelectedItem="{Binding Units}"
    />
当您使用SelectedValue指定您关注的所选项目的属性时,将使用

SelectedValuePath="SomePropertyName"。但枚举没有属性,所以只需抓住项目本身。

这是我ObservableObject的替身:

public class ObservableObject : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged([CallerMemberName] string prop = null)
        => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop));
}

没什么聪明的。我用片段创建了那些。