2010-12-02 27 views

答えて

14

あなたは、コンボボックスのインデックスとバックにブール値に変換するためにValueConverterを使用することができます。このように:はいを想定し

public class BoolToIndexConverter : IValueConverter 
    { 
     public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
     { 
      return ((bool)value == true) ? 0 : 1; 
     } 

     public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
     { 
      return ((int)value == 0) ? true : false; 
     } 
    } 
} 

インデックス0にあり、ノーインデックス1に続いて、あなたはSelectedIndexプロパティへの結合にそのコンバータを使用する必要があると思います。このために、あなたのリソースセクションで、あなたのコンバータを宣言:

<ComboBox SelectedIndex="{Binding YourBooleanProperty, Converter={StaticResource boolToIndexConverter}}"/> 
+0

私は親切でwpfの新人です。ありがとうございました – user434547

+0

あなたのために働いた場合は、それを回答としてマークすることができます。 :) – Botz3000

+0

偉大な答え。この[リンク](http://msdn.microsoft.com/en-us/library/system.windows.data.binding.converter(v = vs.110).aspx)では、この件に関する詳細情報を提供しています。 – estebro

11

最初のソリューションはので、チェックボックスを使用して「はい/いいえ」コンボボックスを交換することである。

<Window.Resources> 
    <local:BoolToIndexConverter x:Key="boolToIndexConverter" /> 
    </Window.Resources> 

は、その後、結合あなたにそれを使用します、まあ、チェックボックスは理由のために存在します。

第2の解決策は、コンボボックスを真偽オブジェクトで塗りつぶしてから、コンボボックスの「SelectedItem」をブール値プロパティにバインドすることです。

+0

あなたの解決策は私には起こりませんでしたので+1しているのかどうかわかりません。 – Jeff

4

私は過去にこのためのコンボボックス項目のIsSelectedプロパティを使用して自分自身を発見しました。このメソッドは完全にxamlです。ここで

<ComboBox> 
    <ComboBoxItem Content="No" /> 
    <ComboBoxItem Content="Yes" IsSelected="{Binding YourBooleanProperty, Mode=OneWayToSource}" /> 
</ComboBox> 
1

は(はい/いいえで有効化/無効化しない置き換える)の例である:

public class EnabledDisabledToBooleanConverter : IValueConverter 
{ 
    private const string EnabledText = "Enabled"; 
    private const string DisabledText = "Disabled"; 
    public static readonly EnabledDisabledToBooleanConverter Instance = new EnabledDisabledToBooleanConverter(); 

    private EnabledDisabledToBooleanConverter() 
    { 
    } 

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     return Equals(true, value) 
      ? EnabledText 
      : DisabledText; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     //Actually won't be used, but in case you need that 
     return Equals(value, EnabledText); 
    } 
} 

そしてインデックスに再生する必要はありません。ここで

<ComboBox SelectedValue="{Binding IsEnabled}"> 
    <ComboBox.ItemTemplate> 
     <DataTemplate> 
      <TextBlock Text="{Binding Converter={x:Static converters:EnabledDisabledToBooleanConverter.Instance}}"/> 
     </DataTemplate> 
    </ComboBox.ItemTemplate> 
    <ComboBox.Items> 
     <system:Boolean>True</system:Boolean> 
     <system:Boolean>False</system:Boolean> 
    </ComboBox.Items> 
</ComboBox> 

はコンバータです。

関連する問題