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>

如何将点击绑定到绑定的底层对象中btnRunTest的方法?RunTest()

4

1 回答 1

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>

另请参阅:如何在 wpf 中使用 RelayCommand?

于 2013-07-29T19:16:52.063 回答