2014-06-21 92 views
2

我正在做一個應用程序在MVVM中,我是新的... 我有一個布爾字段,並希望顯示一個組合框用戶項目是/否但是當用戶選擇它,但在數據上下文值是1和0。 我有以下代碼:mvvm:我應該如何將布爾值綁定到組合框

<TextBlock Grid.Row="2" Grid.Column="2" Text="Batch Flag" Margin="5,0,0,0" /> 
           <ComboBox Grid.Row="2" Grid.Column="3" x:Name="cboBtchFlg" SelectedItem="{Binding SelectedADM_M022.BtchFlg,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" Margin="5,0,0,2" Background="Transparent"> 
            <ComboBoxItem Tag="1">True</ComboBoxItem> 
            <ComboBoxItem Tag="0">False</ComboBoxItem> 
           </ComboBox>  

回答

2

你可以使用一個轉換器。如果視圖模型屬性是一個布爾值,並且它綁定到組合框的SelectedIndex屬性(這是一個int),那麼此示例將提供您需要的。

public class IntToBoolConverter : IValueConverter 
{ 
    // from view model to view 
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     if (value is bool) 
     { 
      bool trueFalse = (bool)value; 
      return trueFalse == true ? 0 : 1; 
     } 
     return value; 
    } 

    // from view to model 
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     if (value is int) 
     { 
      int index = (int)value; 
      if (index == 0) 
       return true; 
      if (index == 1) 
       return false; 
     } 
     return value; 
    } 
} 

修改的SelectedIndex結合

SelectedItem="{Binding SelectedADM_M022.BtchFlg,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged, Converter={StaticResource boolConverter}}" 

給你有資源稱爲boolConverter引用您的轉換器類E,G,

<Window.Resources> 
    <local:IntToBoolConverter x:Key="boolConverter" /> 
</Window.Resources>