2

我正在尝试将按钮的 IsEnabled 属性绑定到窗口的 CollectionViewSource 的属性。我这样做是为了实现第一个/上一个/下一个/最后一个按钮,并希望在视图位于第一个项目等时禁用第一个和上一个。

我已经设置了集合视图源,UI 控件正确绑定到它,并可以在代码中访问它的视图,因此单击事件处理程序在浏览视图时可以正常工作。

      <CollectionViewSource x:Key="cvMain" />

DockPanel 是窗口的根元素

  <DockPanel DataContext="{StaticResource cvMain}">

FoJobs 是一个可观察的集合,cvJobs 是我在按钮的单击处理程序中使用的 CollectionView

private void Window_Loaded(object sender, RoutedEventArgs e) {
  ((CollectionViewSource)Resources["cvMain"]).Source = FoJobs;
  cvJobs = (CollectionView)((CollectionViewSource)Resources["cvMain"]).View;
}

我已经尝试过了,但出现绑定错误“BindingExpression path error: '' property not found on 'object' ''ListCollectionView'”

        <Button Name="cbFirst" Click="cbMove_Click" IsEnabled="{Binding Source={StaticResource cvMain}, Converter={StaticResource CurrPos2BoolConverter}}" />

我首先尝试使用转换器,但认为带有触发器的样式会更有效,但无法访问集合视图。即使底层数据上下文设置为集合视图源,绑定也会作为视图源传递给转换器(如果我没有明确设置绑定的源,如上所述),它没有货币属性(CurrentPosition、Count 等)。

任何帮助将不胜感激。

4

1 回答 1

2

你为什么不使用 a RoutedCommand(即使你不使用 MVVM)?

像这样说:

<Button x:Name="nextButton"
        Command="{x:Static local:MainWindow.nextButtonCommand}"
        Content="Next Button" />

并在您的代码隐藏中:

public static RoutedCommand nextButtonCommand = new RoutedCommand();

public MainWindow() {
  InitializeComponent();
  CommandBinding customCommandBinding = new CommandBinding(
    nextButtonCommand, ExecuteNextButton, CanExecuteNextButton);
  nextButton.CommandBindings.Add(customCommandBinding);  // You can attach it to a top level element if you wish say the window itself
}

private void CanExecuteNextButton(object sender, CanExecuteRoutedEventArgs e) {
  e.CanExecute = /* Set to true or false based on if you want button enabled or not */
}

private void ExecuteNextButton(object sender, ExecutedRoutedEventArgs e) {
  /* Move code from your next button click handler in here */
}

您还可以应用Explicitly raise CanExecuteChanged()中的建议之一来手动重新评估Button.isEnabled状态。

这样,您就可以在一个区域中封装与按钮相关的逻辑。

于 2013-03-31T10:32:07.987 回答