我遇到绑定问题。我不知道怎么做。
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>
在这种情况下,我有错误
&#34; System.Windows.Data错误:4:找不到绑定源 参考&#39; RelativeSource FindAncestor, AncestorType =&#39; ManyViews.ViewModel.ListViewModel&#39;,AncestorLevel =&#39; 1&#39;&#39;。 BindingExpression:路径= DataContext.EventChecked;的DataItem = NULL;目标 元素是&#39; InvokeCommandAction&#39; (的HashCode = 43550996);目标财产 是&#39; Command&#39; (键入&#39; ICommand&#39;)&#34;
答案 0 :(得分:1)
AncestorType={x:Type test:ListViewModel}
是你的问题。
可视树中没有test:ListViewModel
高于当前项目。只有不同的控件,而不是(视图)模型。
将其更改为搜索ListView
:
<i:InvokeCommandAction
Command="{Binding DataContext.EventChecked, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListView}}}">
</i:InvokeCommandAction>