我正在尝试根据listview项数据执行方法。除此之外,触发命令的按钮应该只在listview项的“CanExecute”方法返回true时启用。
“MyCommand”和“CanExecute”两种方法都包含在我的ViewModel中。不幸的是,我不知道如何正确地将项信息传递给这两种方法,以符合PRISM 6框架的要求。
所以我的第一个尝试是像以下方式:
模型
public class MyModel
{
public string Name { get; set; }
public string Version { get; set; }
public int Identifier { get; set; }
}
视图模型
public class MyViewModel : BindableBase
{
private ObservableCollection<MyModel> _models = new ObservableCollection<MyModel>();
public ObservableCollection<MyModel> Models
{
get { return _models; }
set { SetProperty(ref _models, value); }
}
public DelegateCommand VerifyCommand { get; set; }
public MyViewModel()
{
//Add test data
for (int i = 0; i < 5; i++)
{
MyModel model = new MyModel();
model.Name = "Random Text";
model.Version = "Random Text";
model.Identifier = i;
Models.Add(model);
}
//Doesn't work, because I don't reference to "Models"
//How to do that?
VerifyCommand = new DelegateCommand(DoCommand, CanExecute).ObservesProperty<string>(() => Name).ObservesProperty<string>(() => Version);
}
private bool CanExecute()
{
//Obviously this doesn't work, because "Version" and "Name"
//don't belong to the selected "Models" item of the listview
//What is the "bridge", to know which item of Models was clicked (button)
return !String.IsNullOrWhiteSpace(Version) && !String.IsNullOrWhiteSpace(Name);
}
private void DoCommand()
{
//Do something special
}
}
视图
<ListView ItemsSource="{Binding Models}">
<ListView.ItemTemplate>
<DataTemplate>
<Grid Height="Auto" Margin="0,0,0,10">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBox Grid.Row="0" Tag="VERSION" Text="{Binding Version, UpdateSourceTrigger=PropertyChanged}" />
<TextBox Grid.Row="1" Tag="NAME" Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}" />
<Button Command="{Binding ElementName=root, Path=DataContext.VerifyCommand}" Content="Verify" Grid.Row="2">
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
视图和视图模型之间的链接是通过以下方式完成的:
prism:ViewModelLocator.AutoWireViewModel="True"
在我的观点中(这个有效)。
因此,总结一下: PRISM如何符合要求,以便1.仅在CanExecute为true时启用项目按钮,并2.执行“DoCommand”方法并将项目信息传递给该按钮的根元素 -> 在这种情况下是ListViewItem(MyModel)。
任何帮助都将不胜感激。
Models
属性可能不需要 setter,除非你计划从外部(通过数据绑定)设置它... - Haukinger