我有以下代码:
<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
选择了一个或多个项目。
我怎样才能做到这一点?
答案 0 :(得分:2)
如果您使用MVVM模式(应该使用WPF),则应实现ICommand并将其绑定到按钮的Command属性。在按钮的CanExecute方法中,您可以检查列表框的所选项的计数。它在满足条件时自动启用/禁用按钮。这看起来像这样:
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" />
答案 1 :(得分:1)
将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;
}