【发布时间】:2013-07-29 18:52:15
【问题描述】:
我正在尝试将绑定 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()方法?
【问题讨论】:
-
查看
ICommand或我的首选RelayCommand,您应该能够找到许多示例。 -
为了补充@JefferyKhan 在这里所说的内容,这是他正在谈论的一个例子msdn.microsoft.com/en-us/magazine/dd419663.aspx#id0090030
-
为了补充@Bearcat9425 所说的内容,这里有一个更易于阅读的示例:Simplified MVVM Commanding with DelegateCommand :)
标签: c# .net wpf xaml data-binding