【问题标题】:Silverlight implement value converter to comboBoxSilverlight 将值转换器实现为组合框
【发布时间】:2012-12-20 13:46:20
【问题描述】:

我有以下场景

1- xaml 中的组合框

<ComboBox 
x:Name="PublishableCbo" Width="150" IsEnabled="True" HorizontalAlignment="Left" Height="20" 
SelectedValue="{Binding Path=Published, Mode=TwoWay}"
Grid.Column="6" Grid.Row="0">
<ComboBox.Items>
    <ComboBoxItem Content="All"  IsSelected="True" />
    <ComboBoxItem Content="Yes"  />
    <ComboBoxItem Content="No"  />
</ComboBox.Items>

2- 在模型类中,我定义了一个属性并绑定到组合框中的选定值

 public bool Published
    {
      get
      {
        return _published;
      }
      set
      {
        _published = value;
        OnPropertyChanged("Published");
      }
    }

我知道我必须实现一个转换器,但不知道具体如何。 What I want is when a select Yes/No, in the model get a True/false value, when "all" is selected, to get null value.

【问题讨论】:

    标签: silverlight xaml combobox valueconverter


    【解决方案1】:

    为了能够将null 分配给Published 属性,您必须将其类型更改为Nullable< bool >(您可以在C# 中编写bool?)。

    public bool? Published
    {
        ...
    }
    

    可以实现转换器,使其从string 转换为bool,反之亦然,可能如下所示。请注意,转换器使用bool,而不是bool?,因为该值作为object 传入和传出转换器,因此无论如何都要装箱。

    public class YesNoAllConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            object result = "All";
    
            if (value is bool)
            {
                result = (bool)value ? "Yes" : "No";
            }
    
            return result;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            object result = null;
    
            switch ((string)value)
            {
                case "Yes":
                    result = true;
                    break;
                case "No":
                    result = false;
                    break;
            }
    
            return result;
        }
    }
    

    要启用此转换器,您必须将 ComboBox 项目类型更改为 string,并绑定到 SelectedItem 属性,而不是 SelectedValue。

    <ComboBox SelectedItem="{Binding Path=Published, Mode=TwoWay,
                             Converter={StaticResource YesNoAllConverter}}">
        <sys:String>All</sys:String>
        <sys:String>Yes</sys:String>
        <sys:String>No</sys:String>
    </ComboBox>
    

    其中sys 是以下 xml 命名空间声明:

    xmlns:sys="clr-namespace:System;assembly=mscorlib"
    

    【讨论】:

    • 非常感谢!工作完美!如何设置页面加载时默认选择“全部”值?现在我没有 IsSelected 属性
    猜你喜欢
    • 2018-04-23
    • 2011-09-23
    • 2017-02-05
    • 1970-01-01
    • 1970-01-01
    • 2015-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多