我正在尝试将绑定ListView中的按钮单击事件绑定到列表的基础数据源上的方法。我已经搜索了这个,但所有的例子似乎都列出了代码页面,我很确定这可以通过绑定表达式来实现 - 或者至少我希望如此!
基础数据源是此类的集合......
public class AppTest : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
int _priority;
string _testName;
public void RunTest()
{
// TODO: Implement
}
public int Priority
{
get { return _priority; }
set
{
_priority = value;
NotifyPropertyChanged("Priority");
}
}
public string TestName
{
get { return _testName; }
set
{
_testName = value;
NotifyPropertyChanged("TestName");
}
}
protected void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
......而XAML看起来像这样......
<Window.Resources>
<CollectionViewSource x:Key="cvs" x:Name="cvs" Source="">
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="Priority" Direction="Ascending" />
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>
</Window.Resources>
<Grid>
<ListView x:Name="TestList" ItemsSource="{Binding Source={StaticResource cvs}}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<Application:AppTestControl Message="{Binding TestName}" />
<Button x:Name="btnRunTest">
Run Test
</Button>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListView>
</Grid>
如何将btnRunTest
的点击绑定到绑定的基础对象中的RunTest()
方法?
答案 0 :(得分:0)
使用MvvmLight RelayCommand
:
视图模型:
private ICommand _runTestCommand;
public ICommand RunTestCommand()
{
return _runTestCommand ?? (_runTestCommand = new RelayCommand(RunTest));
}
XAML:
<Button x:Name="btnRunTest" Command="{Binding Path=RunTestCommand}">
Run Test
</Button>