启用/禁用Xaml中的ComboBox选择控件

bil*_*ill 2 wpf xaml

如果选择/未选择组合框,如何启用/禁用文本框,标签,文本块等控件?例如,如果所选索引大于零,则启用控件,否则禁用。如何将控件的IsEnabled属性与组合框选择绑定?

Chr*_* W. 7

我可能只会做这样的事情。

<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>
Run Code Online (Sandbox Code Playgroud)

希望这有帮助,干杯!


小智 5

您可以绑定IsEnabledSelectedIndexComboBox 的属性,并使用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}}"/>
Run Code Online (Sandbox Code Playgroud)

然后,您还需要一个转换器,例如:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

您还将已经将Converter声明为资源,例如在Window中。

<local:IndexToBoolConverter x:Key="IndexToBoolConverter"/>
Run Code Online (Sandbox Code Playgroud)