我有一个 WPF/MVVM 应用程序,ListBox
它通过DataTemplate
. 我设法ListBox
在按下按钮时更改了所选项目,因此CommandParameter
链接到ListBox
's SelectedItem
,但我无法以相同的方式正确启用/禁用按钮。例如,如果我有 2 个项目并且按钮应该在一个中启用而在另一个中禁用,当我选择一个元素时,两个按钮具有相同的状态,并且当我选择另一个项目时它们都会改变状态。
我正在使用RelayCommand
许多 MVVM 框架中使用的 a。
这是我的 XAML(删除了“不感兴趣”的部分):
<UserControl.Resources>
<DataTemplate x:Key="ItemTemplate">
<Grid>
<Button Content="Something" Name="EnabledDisabledButton" Click="Button_Click"
Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type UserControl}}, Path=DataContext.SomeCommand}"
CommandParameter="{Binding RelativeSource={RelativeSource AncestorType={x:Type ListBox}}, Path=SelectedItem}"/>
</Grid>
</DataTemplate>
<Style TargetType="{x:Type ListBoxItem}" x:Key="ContainerStyle">
<Setter Property="ContentTemplate" Value="{StaticResource ItemTemplate}" />
</Style>
</UserControl.Resources>
<ListBox x:Name="myListBox" ItemsSource="{Binding ElementList}"
IsSynchronizedWithCurrentItem="True" ItemContainerStyle="{StaticResource ContainerStyle}"/>
我试图将'SelectedItem
作为参数传递给RelayCommand
'CanExecute
方法,但结果和以前一样。
有没有办法将ListBoxItem
按钮“居住”的实际值作为参数传递给命令,因此每个都将由该CanExecute
方法单独处理?如果我得到了它会起作用吗?(现在我正在处理Click
事件以在执行命令之前在列表中选择正确的项目)。
在我的CanExecute
方法中,我正在评估 的某些属性SelectedItem
以启用/禁用相应的按钮。另一种方法是评估所有元素的此属性,但我想不出在 内部执行此操作的方法ViewModel
,然后将结果传达给视图(如果DataTemplate
在项目中使用 a 时甚至可能的话)。
感谢您的输入,问候!