绑定Button.IsEnabled到CollectionView中的当前位置

时间:2013-03-31 06:15:21

标签: wpf binding collectionviewsource

我正在尝试将按钮的IsEnabled属性绑定到窗口的CollectionViewSource的属性。我这样做是为了实现First / Previous / Next / Last按钮,并且当视图在第一个项目上时,希望禁用First和Previous。

我已经设置了集合视图源,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:''属性找不到'object'''ListCollectionView'”

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

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

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

为什么不为此使用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州。

这样你的封装逻辑与一个区域中的按钮有关。