将 True 值绑定到 XAML 中的 SelectedValue

Bind True value to SelectedValue in XAML

假设我有以下 class:

class SimpleData
{
    public string DisplayName { get; set; }
    public bool IsDefault { get; set; }
}

现在我已经将 SimpleData 的列表存储在列表中并将列表设置为 DataContext。我已经像这样绑定到 lit:

<ComboBox x:Name="layoutComboBox" VerticalAlignment="Center" Padding="3,0,3,0" Height="20" Margin="3,0,0,0" MinWidth="100"
ItemsSource="{Binding Path=GridConfigurationProfiles}"
DisplayMemberPath="DisplayName"
SelectedValuePath="IsDefault"
/>

这对 DisplayMemberPath 来说效果很好,但我没有将项目选为默认项目,它有 IsDefault = True.

问题:如何将 SelectedValue 绑定到 True 以便选中具有 IsDefault = True 的项目。如果条件不止一项为真,系统应该采取任何它想要的。

谢谢。

想一想:IsDefault 并非对每个项目都是唯一的。那么,绑定SelectedValue时,如果有多个IsDefault == true的item,ComboBox应该怎么办呢?

此外,SelectedValue 只是由 SelectedValuePath 确定的选定 ComboBox 项的值。

我建议您绑定 SelectedItem 而不是 SelectedValue:

<ComboBox x:Name="layoutComboBox" VerticalAlignment="Center" Padding="3,0,3,0" Height="20" Margin="3,0,0,0" MinWidth="100"
ItemsSource="{Binding Path=GridConfigurationProfiles}"
DisplayMemberPath="DisplayName"
SelectedValuePath="IsDefault"
SelectedItem="{Binding SelectedConfigurationProfile, Mode=TwoWay}"
/>

在视图模型中:

private _selectedConfigurationProfile;
public SimpleData SelectedConfigurationProfile
{
    get { return _selectedConfigurationProfile; }
    set
    {
        if (_selectedConfigurationProfile != value)
        {
            _selectedConfigurationProfile = value;
            //NotifyPropertyChanged("SelectedConfigurationProfile"); if needed
        }
    }
}

public void MethodThatSetsDefault()
{
    SelectedConfigurationProfile = GridConfigurationProfiles.FirstOrDefault(q => q.IsDefault);
}

来自MSDN

The SelectedValuePath property specifies the path to the property that is used to determine the value of the SelectedValue property.

这基本上意味着,如果您像 SelectedValuePath="IsDefault" 那样设置 属性,则 SelectedValue 属性 将是 IsDefault 属性 的值所选项目。

您还需要为 SelectedValue 提供一个值,以便它初始化 SelectedItem。您可以使用绑定或仅将 属性 设置为 true。

<ComboBox x:Name="layoutComboBox"
          VerticalAlignment="Center"
          Padding="3,0,3,0" 
          Height="20"
          Margin="3,0,0,0" MinWidth="100"
          ItemsSource="{Binding Path=GridConfigurationProfiles}"
          DisplayMemberPath="DisplayName"
          SelectedValuePath="IsDefault" 
          SelectedValue="True"/>

尝试使用转换器:

public class Converter:IValueConverter
{
    public object Convert(object value, Type targetType,
                    object parameter, CultureInfo culture)
    {
        IEnumerable<SimpleData> data=value as IEnumerable<SimpleData>;
        if(data==null) return null;
        else return data.First(x=>x.IsDefault);
    }

    public object ConvertBack(object value, Type targetType, 
                  object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

和绑定:

<local:Converter x:Key="converter"/>
<ComboBox SelectedItem="{Binding 
          Converter="{StaticResource converter}}"/>

或与此类似的内容。