我在绑定方面有一些问题。我不知道怎么做。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GalaSoft.MvvmLight;
using ManyViews.Model;
using System.Collections.ObjectModel;
using System.Windows.Input;
using GalaSoft.MvvmLight.Command;
namespace ManyViews.ViewModel
{
class ListViewModel : ViewModelBase
{
public void show()
{
System.Windows.MessageBox.Show("Raise");
}
public ListViewModel()
{
EventChecked = new RelayCommand(() => show());
}
public ICommand EventChecked { get; set; }
public ObservableCollection<ListStruct> ShowList
{
get { return ListM.Items; }
set { ListM.Items = value; RaisePropertyChanged("ShowList"); }
}
ListModel ListM = new ListModel();
}
}
如果需要选择其他上下文,我总是使用静态资源,但是在这种情况下,EventTrigger中没有属性数据上下文。
<UserControl x:Class="ManyViews.View.List"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:test="clr-namespace:ManyViews.ViewModel"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<UserControl.Resources>
<test:ListViewModel x:Key="Test"></test:ListViewModel>
</UserControl.Resources>
<Grid>
<ListView ItemsSource="{Binding ShowList}">
<ListView.ItemTemplate>
<DataTemplate>
<CheckBox Content="{Binding name}">
<i:Interaction.Triggers >
<i:EventTrigger EventName="Checked">
<i:InvokeCommandAction Command="{Binding DataContext.EventChecked, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type test:ListViewModel}}}"></i:InvokeCommandAction>
</i:EventTrigger>
</i:Interaction.Triggers>
</CheckBox>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
在这种情况下我有错误
“ System.Windows.Data错误:4:找不到绑定源
参考'RelativeSource FindAncestor,
AncestorType ='ManyViews.ViewModel.ListViewModel',AncestorLevel ='1''。
BindingExpression:Path = DataContext.EventChecked; DataItem = null;目标
元素是'InvokeCommandAction'(HashCode = 43550996);目标物业
是“命令”(类型为“ ICommand”)”
最佳答案
AncestorType={x:Type test:ListViewModel}
是您的问题。
视觉树中没有test:ListViewModel
高于当前项目。只有不同的控件,没有(视图)模型。
对其进行更改以搜索ListView
:
<i:InvokeCommandAction
Command="{Binding DataContext.EventChecked, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListView}}}">
</i:InvokeCommandAction>