2013-07-29 25 views
0

我試圖將綁定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> 

我怎麼能結合的Click btnRunTest到綁定的底層對象中的RunTest()方法?

+2

查找到'ICommand'或我的偏好'RelayCommand'這你應該能夠找到很多例子。 – Khan

+0

爲了補充@JefferyKhan在這裏說的是他正在談論的一個例子http://msdn.microsoft.com/en-us/magazine/dd419663.aspx#id0090030 – Bearcat9425

+0

爲了補充@ Bearcat9425在這裏說的更簡單閱讀示例:[使用DelegateCommand的簡化MVVM命令](http://relentlessdevelopment.wordpress.com/2010/03/30/simplified-mvvm-commanding-with-delegatecommand/):) – PoweredByOrange

回答

0

使用MvvmLightRelayCommand

視圖模型:

private ICommand _runTestCommand; 

public ICommand RunTestCommand() 
{ 
    return _runTestCommand ?? (_runTestCommand = new RelayCommand(RunTest)); 
} 

XAML:

<Button x:Name="btnRunTest" Command="{Binding Path=RunTestCommand}"> 
    Run Test 
</Button> 

另請參見:How can I use the RelayCommand in wpf?