0

次のシナリオがあります

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");
      }
    }

コンバーターを実装する必要があることはわかっていますが、正確な方法はわかりません。私が欲しいのは、モデルでYes/Noを選択するとTrue/Falseの値が得られ、「すべて」が選択されたときにnull値を取得することです。

4

1 に答える 1

1

プロパティに代入できるようにするにnullは、その型をNullable< bool >に変更する必要があります ( C# で記述できます)。Publishedbool?

public bool? Published
{
    ...
}

stringConverter は、おそらく以下に示すように、から、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 アイテム タイプを に変更し、SelectedValue ではなくSelectedItemプロパティにstringバインドする必要があります。

<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"
于 2012-12-20T14:41:06.543 に答える