【问题标题】:Bind button click to method on underlying datasource将按钮单击绑定到底层数据源上的方法
【发布时间】: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()方法?

【问题讨论】:

标签: c# .net wpf xaml data-binding


【解决方案1】:

使用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?

【讨论】:

    猜你喜欢
    • 2011-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多