2014-04-07 69 views
0

我想問一下,如何根據綁定變量的值選擇Combobox項目。例如綁定布爾變量性別綁定值男性如何根據綁定變量的值選擇ComboBox項目?

<ComboBox> 
    <ComboBoxItem Content="male"/>  <- select if true 
    <ComboBoxItem Content="female" />  <- select if false 
</ComboBox> 
+0

如果我的價值是真實的,那麼我想與內容MALE到selest項目。並且當它是假的時候,我想選擇帶有內容FEMALE的項目。 – Andrew

回答

1

試試這個例子:

<RadioButton Name="Female" 
      Content="Female" 
      Margin="0,0,0,0" /> 

<RadioButton Name="Male" 
      Content="Male" 
      Margin="0,20,0,0" /> 

<ComboBox Width="100" Height="25"> 
    <ComboBoxItem Content="Male" 
        IsSelected="{Binding Path=IsChecked, 
             ElementName=Male}" />   

    <ComboBoxItem Content="Female" 
        IsSelected="{Binding Path=IsChecked, 
             ElementName=Female}" />     
</ComboBox> 

隨着越來越多的通用解決方案,您可以使用Converter

提供一種方法來定製邏輯應用到綁定。

例子:

XAML

<Window x:Class="MyNamespace.MainWindow" 
     xmlns:this="clr-namespace:MyNamespace" 

    <Window.Resources> 
     <this:MaleFemaleConverter x:Key="MaleFemaleConverter" /> 
    </Window.Resources> 

    <ComboBox Width="100" 
       Height="25" 
       SelectedIndex="{Binding Path=IsChecked, <--- Here can be your variable 
             ElementName=SomeElement, 
             Converter={StaticResource MaleFemaleConverter}}"> 

     <ComboBoxItem Content="Male" /> 
     <ComboBoxItem Content="Female" />     
    </ComboBox>  

Code-behind

public class MaleFemaleConverter : IValueConverter  
{   
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)   
    {    
     bool Value = (bool)value; 

     if (Value == true) 
     { 
      return 1; 
     } 

     return 0; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     return DependencyProperty.UnsetValue; 
    }    
} 
+0

它正在工作,但是,如果源不是單選按鈕,而是變量我的變量,你可以如此好,並給我一個提示如何做到這一點? – Andrew

+0

@Andrew:請參閱我的編輯。 –

+1

謝謝你,現在我很高興:) – Andrew

相關問題