2016-06-14 41 views
-1

如果選擇/未選擇組合框,如何啓用/禁用控件(如文本框,標籤,文本塊)?例如如果選擇的索引大於零,則啓用控件其他禁用。如何將控件的IsEnabled屬性與組合框選擇綁定?在Xaml中啓用/禁用組合框選擇上的控件

+0

您綁定了IsEnabled – Paparazzi

+0

@Paparazzi我更新了問題。 – bill

+0

在ComboboxSelection的'PropertyChanged'事件中,您需要更新綁定到要啓用/禁用的控件的IsEnabled屬性的** VM **中的其他屬性。 – Kidiskidvogingogin

回答

2

您可以將IsEnabled綁定到組合框的SelectedIndex屬性,並使用IValueConverter將其轉換爲布爾值。例如,在你的XAML(說明啓用一個Button):

<ComboBox x:Name="cmbBox" ItemsSource="{Binding Source={StaticResource DataList}}"/> 
<Button Grid.Column="1" IsEnabled="{Binding ElementName=cmbBox, Path=SelectedIndex, Converter={StaticResource IndexToBoolConverter}}"/> 

然後,你需要一個轉換器爲好,如:

public class IndexToBoolConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     if ((int)value > 0) 
     { 
      return true; 
     } 
     else 
     { 
      return false; 
     } 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     throw new NotImplementedException(); 
    } 
} 

您還可以聲明轉換爲資源,如在你的窗口中。

<local:IndexToBoolConverter x:Key="IndexToBoolConverter"/> 
1

我可能會做這樣的事情。

<Grid> 
    <Grid.Resources> 
     <Style TargetType="{x:Type Button}"> 
      <Style.Triggers> 
       <DataTrigger Binding="{Binding Path=SelectedItem, 
               ElementName=TheCombo}" 
               Value="{x:Null}"> 
        <Setter Property="IsEnabled" Value="False" /> 
       </DataTrigger> 
      </Style.Triggers> 
     </Style> 
    </Grid.Resources> 

    <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center"> 

     <ComboBox x:Name="TheCombo" Width="100"> 
      <ComboBoxItem>Blah</ComboBoxItem> 
      <ComboBoxItem>Blah</ComboBoxItem> 
      <ComboBoxItem>Blah</ComboBoxItem> 
     </ComboBox> 

     <Button Content="Click Me" Margin="0,10"/> 

    </StackPanel> 

</Grid> 

希望這會有所幫助,歡呼!

相關問題