在两个列表框中都选择了项目时启用按钮

本文关键字:选择 项目 按钮 启用 列表 两个 | 更新日期: 2023-09-27 17:58:52

我有以下代码:

<ListBox x:Name="listbox1" HorizontalAlignment="Left" Height="240" Margin="81,80,0,0" VerticalAlignment="Top" Width="321" BorderBrush="#FF6C6C6C" SelectionMode="Single"/>
<ListBox x:Name="listbox2" HorizontalAlignment="Left" Height="240" Margin="482,80,0,0" VerticalAlignment="Top" Width="318" BorderBrush="#FF6C6C6C" SelectionMode="Multiple"/>
<Button x:Name="uButton" Content="Upload stuff" HorizontalAlignment="Left" Margin="840,178,0,0" VerticalAlignment="Top" Width="160" Height="46" BorderBrush="#FF6C6C6C" Foreground="#FF0068FF" Click="ButtonClick">
    ...
</Button>

我希望使用IsEnable=false禁用按钮uButton,直到用户从listbox1选择一个项目,从listbox2选择一个或多个项目。

我怎样才能做到这一点?

在两个列表框中都选择了项目时启用按钮

如果您使用MVVM模式(您应该使用WPF),您应该实现一个ICommand并将其绑定到按钮的Command属性。在按钮的CanExecute方法中,您可以检查ListBoxes中所选项目的计数。当满足条件时,它会自动启用/禁用您的按钮。这可能看起来像这样:

public class SomeCommand: ICommand
{
    #region Fields
    MainWindow mainWindow;
    #endregion
    #region Constructors and Destructors
    public SomeCommand( MainWindow mw )
    {
        this.mainWindow = mw;
    }
    #endregion
    #region ICommand
    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }
    public bool CanExecute( object parameter )
    {
        return ( this.mainWindow.listbox1.SelectedItems.Count != 0 
                && this.mainWindow.listbox2.SelectedItems.Count != 0 );
    }
    public void Execute( object parameter )
    {
        //DO STUFF;
    }
    #endregion
}

在您的XAML中:

    <ListBox x:Name="listbox1" HorizontalAlignment="Left" Height="240" Margin="81,80,0,0" VerticalAlignment="Top" Width="321" BorderBrush="#FF6C6C6C" SelectionMode="Single"/>
    <ListBox x:Name="listbox2" HorizontalAlignment="Left" Height="240" Margin="482,80,0,0" VerticalAlignment="Top" Width="318" BorderBrush="#FF6C6C6C" SelectionMode="Multiple"/>
    <Button x:Name="uButton" Command="{Binding SomeCommand}" Content="Upload stuff" HorizontalAlignment="Left" Margin="840,178,0,0" VerticalAlignment="Top" Width="160" Height="46" BorderBrush="#FF6C6C6C" Foreground="#FF0068FF" />

SelectionChanged="ListBox_SelectionChanged"添加到xaml代码中的listbox1和listbox2属性中。

IsEnabled="False"添加到按钮属性中

然后在你的代码

private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (listbox1.SelectedItem != null && listbox2.SelectedItems != null)
            ubutton.IsEnabled = true;
        else
            ubutton.IsEnabled = false;
    }