如果在ListView中没有选择任何项,如何禁用按钮

本文关键字:何禁用 按钮 任何项 有选择 ListView 如果 | 更新日期: 2023-09-27 18:14:54

我有一个ListView包含在一个UserControl我想禁用一个按钮时,没有项目在UserControl中选择,这是正确的方法吗?到目前为止,它还没有禁用,它只是一直保持启用。我包含了xaml代码。

searchAccountUserControl是xaml中的UserControl名称属性。AccountListView是userControl xaml中的ListView名称属性。

<Button Content="Debit" IsEnabled="true" HorizontalAlignment="Left" Margin="18,175,0,0" Name="DebitButton" Width="128" Grid.Column="1" Height="32" VerticalAlignment="Top" Click="DebitButton_Click">
        <Button.Style>
            <Style TargetType="Button">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding ElementName=searchAccountUserControl.AccountListView, Path=SelectedValue}" Value="{x:Null}" >
                        <Setter Property="Button.IsEnabled" Value="false"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Button.Style>
    </Button>

谢谢。

最后我用了:

in my ViewModel:

private bool _isSelected;
public bool IsSelected { get { return _isSelected; } 
set { _isSelected = _account.View.CurrentItem != null;       
PropertyChanged.SetPropertyAndRaiseEvent(this, ref _isSelected, value,  
ReflectionUtility.GetPropertyName(() => IsSelected)); } } 

然后在xaml.

如果在ListView中没有选择任何项,如何禁用按钮

中使用isEnabled = "{Binding Path=IsSelected}"

这里有一些错误。

  1. 优先级,如果你在控件本身设置IsEnabled,样式将永远无法改变它。

  2. ElementName,它是一个ElementName,不是一个路径,只是一个字符串,给出一个元素的名称。

  3. 样式语法,如果你设置了Style.TargetType,你不应该设置Setter.Property与类型前缀(尽管留下它不会破坏setter)。

顺便说一下,这个就足够了:

<Button IsEnabled="{Binding SelectedItems.Count, ElementName=lv}" ...

很明显,您没有使用命令(ICommand Interface)。您应该使用它(最好是模型-视图- viewmodel架构)。

但是,如果您想坚持使用代码隐藏和XAML:

<ListView SelectionChanged="AccountListView_SelectionChanged" ... />
private void AccountListView_SelectionChanged(Object sender, SelectionChangedEventArgs args)
{
    DebitButton.IsEnabled = (sender != null);
    //etc ...
}

关于MVVM的更多信息:http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

你需要将View (UserControl)的DataContext设置为你想要使用的ViewModel的实例。然后,从那里,您可以绑定到ViewModel上的属性,包括ICommand。您可以使用RelayCommand(参见上面的链接)或使用框架提供的command(例如,Prism提供了DelegateCommand)。这些命令接受一个Action (Execute)和一个Func (CanExecute)。只需在CanExecute中提供逻辑。当然,你也必须有你的ListView SelectedItem(或SelectedValue)绑定到你的ViewModel上的属性,这样你就可以检查,看看它是否为空在你的CanExecute函数。

假设你使用RelayCommand,你不需要显式调用ICommandRaiseCanExecuteChanged

public class MyViewModel : ViewModelBase //Implements INotifyPropertyChanged
{
    public MyViewModel()
    {
        DoSomethingCommand = new RelayCommand(DoSomething, CanDoSomething);
    }
    public ObservableCollection<Object> MyItems { get; set; }
    public Object SelectedItem { get; set; }
    public RelayCommand DoSomethingCommand { get; set; }

    public void DoSomething() { }
    public Boolean CanDoSomething() { return (SelectedItem != null); }
}
<ListView ItemsSource="{Binding MyItems}" SelectedItem="{Binding SelectedItem}" ... />
<Button Command="{Binding DoSomethingCommand}" ... />