XAML ComboBox默认SelectedIndex未显示

时间:2013-08-23 21:29:14

标签: xaml windows-store-apps

我有一个带有一些值的ComboBox,我想要同时处理两件事。

这是我的ComboBox,我想将10显示为默认值,并将其绑定到double?距离财产。

<ComboBox Grid.Row="5" Grid.Column="1"
          SelectedIndex="1"
          SelectedValue="{Binding Distance, Mode=TwoWay, Converter={StaticResource StringToDoubleConverter}}">
    <ComboBoxItem>1</ComboBoxItem>
    <ComboBoxItem IsSelected="True">10</ComboBoxItem>
    <ComboBoxItem>100</ComboBoxItem>
    <ComboBoxItem>1000</ComboBoxItem>
</ComboBox>

这是转换器:

public class StringToDoubleConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        return null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        ComboBoxItem item = value as ComboBoxItem;

        if (item != null)
        {
            double d;
            if (double.TryParse(item.Content.ToString(), out d))
                return d;
        }

        return null;
    }
}

问题在于,在此代码中,所选项目10未在应用程序的开头显示。 如果我将删除转换器的行,那么它将显示所选的项目10,但是,我不能将它绑定到双精度?距离财产。我不想为它编写代码,例如:Convert.ToDouble(combobox1.SelectedValue)...

我可以做些什么来使两件事都有效?

1 个答案:

答案 0 :(得分:0)

您需要从ViewModel填充组合框项目。此外,您不应使用SelectedValue属性,而应使用SelectedItem。请参阅下面给出的代码。

XAML

<ComboBox x:Name="cmb" ItemsSource="{Binding DistanceCollection}"
                     SelectedItem="{Binding Distance, Converter={StaticResource StringToDoubleConverter}, Mode=TwoWay}"/>

视图模型

public class viewModel : INotifyPropertyChanged
{
    public viewModel()
    {
        DistanceCollection = new ObservableCollection<string> 
        {
            "1",
            "10",
            "100",
            "1000"
        };

        Distance = double.Parse(DistanceCollection[1].ToString());
    }

    public ObservableCollection<string> DistanceCollection { get; set; }

    private double _Distance;
    public double Distance
    {
        get 
        { 
            return _Distance; 
        }
        set
        {
            _Distance = value;
            OnPropertyChanged("Distance");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propertyName = null)
    {
        var eventHandler = this.PropertyChanged;
        if (eventHandler != null)
        {
            eventHandler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

转换器

public class StringToDoubleConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        return value.ToString();
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        string item = value as string;

        if (!string.IsNullOrWhiteSpace(item))
        {
            double d;
            if (double.TryParse(item, out d))
                return d;
        }

        return null;
    }
}